【剑指offer】反转链表
输入一个链表,反转链表后,输出新链表的表头。
分析:
方法1:
可以利用栈来做,其实递归也是一个栈,叫做递归栈
方法2:
双指针迭代法,分别指针节点的前驱和后继
func reverseList(head *ListNode) *ListNode {
var p1 *ListNode
p1=nil
p2:=head
for p2!=nil{
next:=p2.Next
p2.Next=p1
p1=p2
p2=next
}
return p1
}
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } };*/ class Solution { public: ListNode* ReverseList(ListNode* pHead) { if(pHead==NULL||pHead->next==NULL) return pHead; ListNode *root=ReverseList(pHead->next); pHead->next->next=pHead; pHead->next=NULL; return root; } };
心之所向,素履以往