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

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

lintcode: Reverse Linked List_空间复杂度

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

参考:​​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;
}
};