zoukankan      html  css  js  c++  java
  • Reverse Linked List****

    Reverse a singly linked list.

    click to show more hints.

    Hint:

    A linked list can be reversed either iteratively or recursively. Could you implement both?

    分析:p = p->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* p = head;
    13         ListNode* current = NULL;
    14         while(p!=NULL)
    15         {
    16             ListNode* newNode = p;
    17             p = p->next;
    18             newNode->next = current;
    19             current = newNode;
    20         }
    21         return current;
    22     }
    23 };

    Runtime: 8ms

     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 || !head->next) return head;
    13         
    14         ListNode* pre = head;
    15         ListNode* current = pre->next;
    16         pre->next = NULL;
    17         while(current){
    18             ListNode* post = current->next;
    19             current->next = pre;
    20             pre = current;
    21             current = post;
    22         }
    23         return pre;
    24     }
    25 };
  • 相关阅读:
    ICPC-Beijing 2006 狼抓兔子
    【模板】多项式求逆
    AHOI2014/JSOI2014 奇怪的计算器
    Hnoi2013 切糕
    Ahoi2014&Jsoi2014 支线剧情
    bzoj3774 最优选择
    WC2019游记
    HNOI2007 分裂游戏
    bzoj1457 棋盘游戏
    poj2484 A Funny Game
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4489193.html
Copyright © 2011-2022 走看看