zoukankan      html  css  js  c++  java
  • 206, Reverse Linked List

     

    Question: Assume that we have linked list 1 → 2 → 3 → Ø, we would like to change it to Ø ← 1 ← 2 ← 3

    Official Solution: While you are traversing the list, change the current node's next pointer to point to its previous element. Since a node does not have reference to its previous node, you must store its previous element beforehand. You also need another pointer to store the next node before changing the reference. Do not forget to return the new head reference at the end!

    public class Solution {
        public ListNode reverseList(ListNode head) {
            ListNode curr = head;
            ListNode prev = null;
            
            while(curr != null) {
                //缓存next,因为倒叙会改变curr.next
                ListNode next_node = curr.next;
                //将curr.next指向prev,即倒序
                curr.next = prev;
                //之后两步是两次移位。prev移到curr,curr移到下一个
                prev = curr;
                curr = next_node;
            }
            return prev;
        }
    }
    

      

  • 相关阅读:
    hadoop中map和reduce的数量设置问题
    Flink基础
    Leetcode中的SQL题目练习(二)
    Redis-2- 基本概念
    Redis-1-安装
    C#事件(1)
    java(13)内部类
    java(12)异常处理
    java(11)构造器
    java(10)接口抽象类
  • 原文地址:https://www.cnblogs.com/Raymond-Yang/p/5163719.html
Copyright © 2011-2022 走看看