Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
思路:每一次翻转 当前节点的下一个结点指向它的前一个结点;它的下一个结点的指针指向它;
ListNode *cur=head;
ListNode *pre=nullptr;
ListNode *pNext=cur->next;
反转的时候:cur->next=pre;pre=cur;cur=pNext(原来的cur->next);
然后 cur反复的循环 从头往后遍历;
CODE:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head)
{
if(head==nullptr)
return nullptr;
ListNode *pre=nullptr;
ListNode *cur=head;
while(cur)
{
ListNode *pNext=cur->next;
cur->next=pre;
pre=cur;
cur=pNext;
}
return pre;
}
};