zoukankan      html  css  js  c++  java
  • [LeetCode-JAVA] Reverse Linked List I && II

    题目I:

    Reverse a singly linked list

    思路:建立三个指针,一个用来维护链表头,另外两个再循环中,维护head的前一位和保存反转的后一位。

             逐个反转,首先反转前两个,然后把前两个看成是一个,继续循环反转下去。

    代码:

    public class Solution {
        public ListNode reverseList(ListNode head) {
                   ListNode dunmy = head;  //维护初始链表头,用于判断循环结束
            
            if(head == null || head.next == null)
                return head;
            ListNode pre = null;
            ListNode temp = null;
            while(dunmy.next != null){
                pre = head;              //记录当前节点
                head = dunmy.next;
                temp = head.next;   //保存next
                head.next = pre;
                dunmy.next = temp;
            }
            
            return head;
        }
    }

    题目II:

    Reverse a linked list from position m to n. Do it in-place and in one-pass.

    For example:
    Given 1->2->3->4->5->NULLm = 2 and n = 4,

    return 1->4->3->2->5->NULL.

    Note:
    Given mn satisfy the following condition:
    1 ≤ m ≤ n ≤ length of list.

    思路:在I的基础上,没有太大的变化,找到开始的位置后,进行反转。

            需要注意的是建立一个虚拟链表头,这样在连接的时候比较方便。

    代码:

    public class Solution {
        public ListNode reverseBetween(ListNode head, int m, int n) {
            ListNode pre = new ListNode(0);  //虚拟链表头
            pre.next = head;
            ListNode dunmy = pre;
            int len = n-m;
            while(m > 1){  // 找到反转的位置
                head = head.next;
                pre = pre.next;
                m--;
            }
            pre.next = reverse(head, len);  //进行连接
            
            return dunmy.next;
        }
        public ListNode reverse(ListNode head, int n){
            ListNode dunmy = head;
            
            if(head == null || head.next == null)
                return head;
            ListNode pre = null;
            ListNode temp = null;
            while(n > 0){
                pre = head;
                head = dunmy.next;
                temp = head.next;
                head.next = pre;
                dunmy.next = temp;
                n--;
            }
            
            return head;
        }
    }
  • 相关阅读:
    javascript中数组去重的4种方法
    dede使用方法----实现英文版的搜索功能
    dede去掉当前位置position后面的箭头
    dede使用方法----如何转换时间戳
    Python字符串、元组、列表、字典互相转换的方法
    Python 列表的操作
    Python 元祖的操作
    Python 操作文件、文件夹、目录大全
    python文件目录操作大全
    python用time函数计算程序运行时间
  • 原文地址:https://www.cnblogs.com/TinyBobo/p/4515450.html
Copyright © 2011-2022 走看看