问题描述
输入一个链表,反转链表后,输出新链表的表头。
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 == NULL) return pHead; 13 ListNode *cur = pHead, *nxt, *pre = NULL; 14 while(cur != NULL){ 15 nxt = cur->next; 16 cur->next = pre; 17 pre = cur; 18 cur = nxt; 19 } 20 return pre; 21 } 22 };
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 not pHead: 11 return pHead 12 cur, pre = pHead, None 13 while cur: 14 nxt = cur.next 15 cur.next = pre 16 pre = cur 17 cur = nxt 18 return pre