您的位置:首页 > 其它

【Leetcode206】 Reverse Linked List

2016-07-15 16:54 225 查看

题目

将单链表逆置

分析

可采用递归和迭代两种思想,注意递归指针变换过程。

代码

1.迭代

/**
* 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 || !head->next) return head;
ListNode *p=head;
ListNode *head_temp=p->next;
while(head_temp){
ListNode *tmp=head_temp->next;
head_temp->next=p;
p=head_temp;
head_temp=tmp;
}
head->next=NULL;
return p;
}
};


2.递归

/**
* 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 || !head->next)
return head;
ListNode *new_head=reverseList(head->next);
head->next->next=head;   //串联已逆置部分和head
head->next=NULL;
return new_head;      //返回最底层递归得到的head
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: