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

    Reverse a singly linked list.

    Thoughts:

    1.Iterative Method.

    Loop the linked list, set two pointers, one called "first" to always point to the head of the list, the other called "tail" to mark the currently looped element, each time we loop to that element, we switch the first and tail element to iteratively finish the reverse function.

    Code:

        public ListNode reverseList(ListNode head) {
            ListNode first = null;
            ListNode tail = head;
                  ListNode tmp;
            while(tail!=null){
      
            tmp=first;
            first = tail;
            tail=tail.next;
            first.next=tmp;
            }
            
            return first;
        }

    2.Recursive Method

    There's code in one reply that spells it out, but you might find it easier to start from the bottom up, by asking and answering tiny questions (this is the approach in The Little Lisper):

    1. What is the reverse of null (the empty list)? null.
    2. What is the reverse of a one element list? the element.
    3. What is the reverse of an n element list? the reverse of the second element on followed by the first element.

    Code:

    public ListNode Reverse(ListNode list)
    {
        if (list == null) return null; // first question
    
        if (list.next == null) return list; // second question
    
        // third question - in Lisp this is easy, but we don't have cons
        // so we grab the second element (which will be the last after we reverse it)
    
        ListNode secondElem = list.next;
    
        // bug fix - need to unlink list from the rest or you will get a cycle
        list.next = null;
    
        // then we reverse everything from the second element on
        ListNode reverseRest = Reverse(secondElem);
    
        // then we join the two lists
        secondElem.Next = list;
    
        return reverseRest;
    }
  • 相关阅读:
    [Head First Python]2. BIF(内置函数)
    [转]mac下Python升级到指定的版本
    [Head First Python]2. python of comment
    自动化测试-----Python基础
    自动化测试----python等工具下载、测试环境搭配、常用的DOS命令
    Python初识与安装
    Python网络爬虫部分
    不知道数据库中表的列类型的前提下,使用JDBC正确的取出数据
    如何做好测试接口
    测试登录界面
  • 原文地址:https://www.cnblogs.com/midan/p/4656006.html
Copyright © 2011-2022 走看看