逆転のリスト
- 反復的なアプローチを実装
https://zhuanlan.zhihu.com/p/48405334で引用ピクチャー
/**
* 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) {
ListNode *curPe = NULL;
ListNode *cur = head;
ListNode *curNe;
while(cur!=NULL)
{
curNe = cur->next;
cur->next = curPe;
curPe = cur;
cur = curNe;
}
return curPe;
//curpe cur curNe三个指针一直保持着这个次序,最后当cur指向NULL时,结束。反转后的头节点为curPe。
}
};
- 達成するための再帰的な方法
/**
* 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||head->next==NULL)
return head;
ListNode *p = reverseList(head->next);
head->next->next =head;
head->next =NULL;
return p;
}
};