思路:设置一个头节点,把之前链表的值一个一个插入到头节点后面,直到插到空!!
不明白为啥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 };
知识兔