15.反转链表

题目描述

输入一个链表,反转链表后,输出新链表的表头。
 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 == nullptr) return nullptr;//头结点为空,直接返回
13     ListNode *pre , *cur , *back;//三个指针保存当前、之前和之后的节点
14         pre = nullptr;
15         cur = pHead;
16         while(cur != nullptr){
17             back = cur->next;
18             cur->next = pre;
19             pre = cur;
20             cur = back;
21         }
22        // cur->next = pre;
23         return pre; //注意头节点的判断
24     }
25 };

 

posted @ 2019-05-19 16:23  unique_ptr  阅读(108)  评论(0编辑  收藏  举报