zoukankan      html  css  js  c++  java
  • 【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 };
  • 相关阅读:
    Jungle Roads POJ 1251
    Light OJ 1234 Harmonic Number
    同余定理
    HDU---1052---田忌赛马
    田忌赛马---空手道俱乐部
    poj---1182---食物链
    Convenient Location(最短路之弗洛伊德)
    js动画实现透明度动画
    js动画实现侧边栏分享
    AngularJS 指令(使浏览器认识自己定义的标签)
  • 原文地址:https://www.cnblogs.com/huxiao-tee/p/4291196.html
Copyright © 2011-2022 走看看