• Java for LeetCode 092 Reverse Linked List 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->NULL, m = 2 and n = 4,

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

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

    解题思路:

    指针操作即可,旋转参考Java for LeetCode 025 Reverse Nodes in k-Group JAVA实现如下:

    static public ListNode reverseBetween(ListNode head, int m, int n) {
    		ListNode result = new ListNode(0);
    		result.next = head;
    		if (m >= n || m <= 0)
    			return result.next;
    		head = result;
    		for (int i = 0; i < m - 1; i++)
    			head = head.next;
    		Stack<Integer> stk = new Stack<Integer>();
    		ListNode temp = head.next;
    		for (int i = 0; i <= n - m; i++)
    			if (temp != null) {
    				stk.push(temp.val);
    				temp = temp.next;
    			}
    		if (stk.size() == n - m + 1) {
    			while (!stk.isEmpty()) {
    				head.next = new ListNode(stk.pop());
    				head = head.next;
    			}
    			head.next = temp;
    		}
    		return result.next;
    	}
    
  • 相关阅读:
    ASP.NET 作业题
    作业题
    作业题...
    作业题
    控件属性
    ASP控件解释
    排序
    5. 用自己的语言描述一下程序连接数据库的过程。
    4. 什么是AJAX
    3.怎样计算页面执行的时间?
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4516613.html
Copyright © 2020-2023  润新知