Comment on page
206.Reverse Linked List
206.Reverse Linked List
难度:Easy
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶: 你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
递归: 由于递归都是一层一层处理的,如果要递归,首先要处理最后一个节点,然后将剩余的继续反转,代码如下:
/**
* 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) return NULL;
if(!head->next) {head->next=NULL; return head;}
ListNode* pt=head;
while(pt->next->next)
{
pt=pt->next;
}
ListNode* t=pt->next;
pt->next=NULL;
t->next=reverseList(head);
return t;
}
};
迭代: 在遍历列表时,将当前节点的下一个节点之前前一个元素,实现反转:
/**
* 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) return NULL;
ListNode* prev=NULL;
ListNode* curr=head;
while(curr!=NULL)
{
ListNode* tmp=curr->next;
curr->next=prev;
prev=curr;
curr=tmp;
}
return prev;
}
};
Last modified 1yr ago