Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
My C++ solution!
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
ListNode* reverseList(ListNode* head)
{
ListNode *p1,*p2,*p3;
if(head==NULL||head->next==NULL)
return head;
p1=head;
p2=p1->next;
while(p2) //注意条件
{
p3=p2->next; //要改变p2->next的指针,所以必须先保留p2->next
p2->next=p1;
p1=p2; //循环往后
p2=p3;
}
head->next=NULL; //原先的head已经变成tail,别忘了置空,只有到这步才能置空
head=p1;
return head;
}