剑指offer——26反转链表
题目描述
输入一个链表,反转链表后,输出新链表的表头。
题解:
每次只反转一个节点,先记住cur->next, 然后pre->cur,即可;
1 class Solution { 2 public: 3 ListNode* ReverseList(ListNode* pHead) { 4 if (pHead == nullptr || pHead->next == nullptr)return pHead; 5 ListNode *pre = nullptr, *cur = nullptr, *next = nullptr; 6 cur = pHead; 7 while (cur != nullptr) 8 { 9 next = cur->next; 10 cur->next = pre; 11 pre = cur; 12 cur = next; 13 } 14 return pre; 15 } 16 };