思路:設置一個頭節點,把之前鏈表的值一個一個插入到頭節點后面,直到插到空!!
不明白為啥t=t->next;要放在第二行!!!
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* reverseList(ListNode* head) { 12 ListNode *phead=new ListNode(-1);//注意第6行listNode(int x)中括號要寫值,這里隨便寫,因為頭節點的val不重要 13 phead->next=NULL;//申請一個頭節點,在空結點后插入值 14 ListNode *ptemp;//臨時結點,存放插入的值 15 ListNode *t;//控制插入節點的值 16 t=head;//從第一個結點開始 17 while(t!=NULL){ 18 ptemp=t; 19 t=t->next; 20 ptemp->next=phead->next; 21 phead->next=ptemp; 22 } 23 return phead->next; 24 } 25 };