题目描述
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
解答 By 海轰
提交代码
/**
* 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 head;
ListNode* p=head;
ListNode* q=head->next;
p->next=NULL;
ListNode* temp;
while(q)
{
temp=q;
q=q->next;
temp->next=p;
p=temp;
}
return p;
}
};
运行结果
思路
简单说来,就是将原链表一个一个再移出,重新添加在另一链表的头部。
解答
- 递归
- 迭代
迭代
/**
* 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* p=NULL;
ListNode* q=head;
while(q)
{
ListNode* temp=q->next;
q->next=p;
p=q;
q=temp;
}
return p;
}
};
递归
/**
* 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* cur=reverseList(head->next);
head->next->next=head;
head->next=NULL;
return cur;
}
};
思路详解🙃