- [牛客網-反轉連結清單](https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca)
給定一個單連結清單的頭結點pHead(該頭節點是有值的,比如在下圖,它的val是1),長度為n,反轉該連結清單後,傳回新連結清單的表頭。
資料範圍: 要求:空間複雜度 ,時間複雜度 。
如當輸傳入連結表{1,2,3}時,經反轉後,原連結清單變為{3,2,1},是以對應的輸出為{3,2,1}。
示例1
輸入:
{1,2,3}
複制傳回值:
{3,2,1}
複制
示例2
輸入:
{}
複制傳回值:
{}
複制說明:
空連結清單則輸出空
struct ListNode
{
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(nullptr)
{
}
};
class Solution
{
public:
ListNode *ReverseList(ListNode *pHead)
{
auto cur_node = pHead;
ListNode *pre_node = nullptr;
ListNode *next_node = nullptr;
while (cur_node != nullptr)
{
next_node = cur_node->next;
cur_node->next = pre_node;
pre_node = cur_node;
cur_node = next_node;
}
return pre_node;
}
};