• LeetCode.206(反转链表)


    LeetCode.206(反转链表) - 简单

    • 反转一个单链表。

    • 示例:

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

      //2020_04_21
      //双指针
      //null   5 -> 4 -> 3 -> 2 -> 1 -> null
      //  cur  pre
      //null <- 5 -> 4 -> 3 -> 2 -> 1 -> null
      //       cur  pre
      //...
      //null <- 5 <- 4 <- 3 <- 2 <- 1    null
      //                           cur   pre
      /**
       * Definition for singly-linked list.
       * struct ListNode {
       *     int val;
       *     ListNode *next;
       *     ListNode(int x) : val(x), next(NULL) {}
       * };
       */
      class Solution {
      public:
          ListNode *reverseList(ListNode *head)
          {
              ListNode *cur = NULL;
              ListNode *pre = head;
              ListNode *t;
              while(pre){
                  t = pre->next;
                  pre->next = cur;
                  cur = pre;
                  pre = t;
              }
              return cur;
          }
      };
      
    • 代码2:

      //2020_04_21
      //栈
      /**
       * Definition for singly-linked list.
       * struct ListNode {
       *     int val;
       *     ListNode *next;
       *     ListNode(int x) : val(x), next(NULL) {}
       * };
       */
      class Solution {
      public:
          ListNode* reverseList(ListNode* head) {
              if(!head) return NULL;//head为空
              ListNode* res, *t;
              stack <int> s;
              while(head){//依次压栈
                  s.push(head -> val);
                  head = head -> next;
              }
              res = new ListNode(s.top());//由于没有头节点,先取出第一个
              s.pop();
              t = res;
              while(!s.empty()){//依次取出
                  t -> next = new ListNode(s.top());
                  t = t -> next;
                  s.pop();
              }        
              return res;//返回结果
          }
      };
      
    • 结果:

  • 相关阅读:
    迷 宫
    车厢调度
    快速幂
    2804 最大最小数质因数
    3022 西天收费站
    2291 糖果堆
    1464 装箱问题 2
    Exists/In/Any/All/Contains操作符
    window.onscroll
    zIndex 属性设置元素的堆叠顺序。
  • 原文地址:https://www.cnblogs.com/iceix/p/12743896.html
Copyright © 2020-2023  润新知