zoukankan      html  css  js  c++  java
  • 206. 反转链表

    在遍历链表时,将当前节点的 next 指针改为指向前一个节点。由于节点没有引用其前一个节点,因此必须事先存储其前一个节点。在更改引用之前,还需要存储后一个节点。最后返回新的头引用。

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode() : val(0), next(nullptr) {}
     *     ListNode(int x) : val(x), next(nullptr) {}
     *     ListNode(int x, ListNode *next) : val(x), next(next) {}
     * };
     */
    
    class Solution {
    public:
        ListNode* reverseList(ListNode* head) {
            ListNode* cur = head;
            ListNode* pre = NULL;
            while(cur != NULL)
            {
                ListNode* temp = cur->next;
                cur->next = pre;
                pre = cur;
                cur = temp;
            }
            return pre;
        }
    };
    
    /*
     * @lc app=leetcode.cn id=206 lang=java
     *
     * [206] 反转链表
     */
    
    // @lc code=start
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode() {}
     *     ListNode(int val) { this.val = val; }
     *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */
    class Solution {
        public ListNode reverseList(ListNode head) {
            ListNode pre = null, cur = head;
            while (cur != null) {
                ListNode next = cur.next;
                cur.next = pre;
                pre = cur;
                cur = next;
            }
            return pre;
        }
    }
    // @lc code=end
  • 相关阅读:
    checkbox的checked事件的javascript使用方法
    JSTL标签API(c)的使用
    radios控件的使用
    验证方法判斷input是否为空
    软件课设Day5
    软件课设Day4
    软件课设Day3
    软件课设Day2
    软件课设Day1
    2019/08/23最新进展
  • 原文地址:https://www.cnblogs.com/fxh0707/p/14663682.html
Copyright © 2011-2022 走看看