zoukankan      html  css  js  c++  java
  • 剑指24: 反转链表

    定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。

    示例:

    输入: 1->2->3->4->5->NULL
    输出: 5->4->3->2->1->NULL
     

    限制:

    0 <= 节点个数 <= 5000

    没有什么聪明的办法,关键在于保证链表不要断开,同时处理链表只有一个头或者直接为空指针的情况,此外最后返回的应该是原链表的尾。

    注意处理原链表头的next指针,修改为nullptr。

     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==nullptr || head->next==nullptr)
    13             return head;
    14         ListNode *curptr, *nextptr, *nextnextptr;
    15         curptr=head;
    16         nextptr=head->next;
    17         nextnextptr=nextptr->next;
    18         head->next=nullptr;
    19         while(nextnextptr!=nullptr){
    20             nextptr->next=curptr;
    21             curptr=nextptr;
    22             nextptr=nextnextptr;
    23             nextnextptr=nextnextptr->next;
    24         }
    25         nextptr->next=curptr;
    26         return nextptr;
    27     }
    28 };
  • 相关阅读:
    JZOJ 3845. 简单题(simple)
    JZOJ 3844. 统计损失(count)
    JZOJ 3843. 寻找羔羊(agnus)
    JZOJ 3833. 平坦的折线
    JZOJ 1956. 矩形
    JZOJ 3832. 在哪里建酿酒厂
    mysql 语法一 :case when详解
    阿里云推荐码
    redis配置文件详解(转)
    压力测试工具 webbench总结
  • 原文地址:https://www.cnblogs.com/rookiez/p/13233250.html
Copyright © 2011-2022 走看看