每日编程-20170509

it2022-05-06  9

题目描述输入一个链表,反转链表后,输出链表的所有元素。

解答:关键是要保存表头

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||pHead->next == NULL) return pHead; 13 ListNode *First = pHead->next->next,*Sec = pHead->next,*Trd = pHead; 14 while(First!=NULL){ 15 Sec->next = Trd; 16 Trd = Sec; 17 Sec = First; 18 First = First->next; 19 } 20 Sec->next = Trd; 21 Trd = Sec; 22 pHead->next = NULL; 23 return Sec; 24 } 25 };

 

转载于:https://www.cnblogs.com/linhaowei0389/p/6832478.html


最新回复(0)