反转链表
c++
栈方法
1 /* 2 struct ListNode { 3 int val; 4 struct ListNode *next; 5 ListNode(int x) : 6 val(x), next(NULL) { 7 } 8 };*/ 9 class Solution { 10 public: 11 ListNode* ReverseList(ListNode* pHead) { 12 if(!pHead || !pHead->next) return pHead; 13 stack<ListNode*> res; 14 ListNode* p = pHead; 15 ListNode* newhead; 16 while(p->next){ 17 res.push(p); 18 p = p->next; 19 } 20 //此时p是最后一个结点 21 newhead = p; 22 while(!res.empty()){ 23 p->next = res.top(); 24 p = p->next; 25 res.pop(); 26 } 27 //此时p到了反转之后的最后一个结点 28 p->next = NULL; 29 return newhead; 30 } 31 };
python
指针法
1 # -*- coding:utf-8 -*- 2 # class ListNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.next = None 6 class Solution: 7 # 返回ListNode 8 def ReverseList(self, pHead): 9 # write code here 10 if pHead==None or pHead.next==None: 11 return pHead 12 last = None 13 cur = pHead 14 while cur!=None: 15 temp = cur.next 16 cur.next = last 17 last = cur 18 cur = temp 19 return last