您的位置:首页 > 其它

lintcode: Reverse Linked List

2016-03-10 10:10 387 查看
Reverse a linked list.

For linked list 1->2->3, the reversed linked list is 3->2->1

Reverse it in-place and in one-pass

最先应该想到的是用栈先依次存储起来,然后弹栈。然而空间复杂度不满足要求。



其实,先保存第二个指针的下一个指针,再翻转两个指针之间的指向就可以达到原地翻转的目的。

参考:http://www.thinksaas.cn/group/topic/395495/

/**
* Definition of ListNode
*
* class ListNode {
* public:
*     int val;
*     ListNode *next;
*
*     ListNode(int val) {
*         this->val = val;
*         this->next = NULL;
*     }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @return: The new head of reversed linked list.
*/
ListNode *reverse(ListNode *head) {
// write your code here

if(head==NULL||head->next==NULL){
return head;
}

ListNode *p1=head;
ListNode *p2=head->next;

while(p2){
ListNode *p2next=p2->next;

if(p1==head){
p1->next=NULL;
}

p2->next=p1;
p1=p2;
p2=p2next;
}

//return p2;
return p1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: