版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/shiliang97/article/details/102089354
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?
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/reverse-linked-list 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
三地址存储 , 前一个,当前,后一个。
while(cur != NULL){ temp = cur->next; cur -> next = pre; pre = cur; cur =temp; }
/**
* 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 == NULL) return NULL;
ListNode *pre = NULL, *cur = head , *temp =NULL;
while(cur != NULL){
temp = cur->next;
cur -> next = pre;
pre = cur;
cur =temp;
}
return pre;
}
};
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==NULL)
return NULL;
ListNode *prePtr = NULL, *curPtr = head, *nextPtr=head->next;
while(nextPtr != NULL){
curPtr->next = prePtr;
prePtr = curPtr;
curPtr = nextPtr;
nextPtr = nextPtr->next;
}
curPtr->next=prePtr;
return curPtr;
}
};
作者:varyshare 链接:https://leetcode-cn.com/problems/reverse-linked-list/solution/gao-xiao-jie-fa-da-bai-9999de-yong-hu-fan-zhuan-li/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。