【Leetcode】【Easy】Reverse Linked List

题目:

Reverse a singly linked list.

解题:

反转单链表,不再多介绍了.

如果会“先条件->定参数->确定不变式->验证后条件”的思维方法,一定会bug free.

 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         if (head == NULL || head->next == NULL)
13             return head;
14             
15         ListNode* newhead = head;
16         ListNode* curNode = NULL;
17         head = head->next;
18         newhead->next = NULL;
19         
20         while (head) {
21             curNode = head;
22             head = head->next;
23             curNode->next = newhead;
24             newhead = curNode;
25         }
26         
27         return newhead;
28     }
29 };

写完初始版本后,再考虑如何去除循环前冗余的赋值,洁简代码:

 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         if (head == NULL || head->next == NULL)
13             return head;
14             
15         ListNode* newhead = NULL;
16         ListNode* nextNode = NULL;
17         
18         while (head) {
19             nextNode = head->next;
20             head->next = newhead;
21             newhead = head;
22             head = nextNode;
23         }
24         
25         return newhead;
26     }
27 };
原文地址:https://www.cnblogs.com/huxiao-tee/p/4291196.html