链表结构
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
leetcode 206
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
思路:
迭代
设置两个指针(new_head和next),new_head始终使其指向新链表的头结点,next始终使其指向待反转链表的头结点。
步骤图示如下(渣绘)
代码如下:
/**
* 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)||(head->next==nullptr))
return head;
ListNode * new_head=nullptr,*next=nullptr;
while(head){
//next指向待排序链表的头结点
next=head->next;
//令被拆下来的节点的next指针指向新链表的头结点
head->next=new_head;
//移动new_head,使其保持指向新链表的头结点
new_head=head;
//使head指向待排序链表的头结点
head=next;
}
return new_head;
}
};
递归
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *helper(ListNode *head) {
ListNode *newHead =nullptr;
if((head==NULL)||(head->next==NULL))
return head;
newHead = helper(head->next);
head->next->next=head;
head->next=NULL;
return newHead;
}
ListNode* reverseList(ListNode* head) {
if((head==nullptr)||(head->next==nullptr))
return head;
ListNode * tail=head;
while(tail->next){
tail=tail->next;
}
helper(head);
return tail;
}
};