首页 > 编程语言 > 详细

Java for LeetCode 092 Reverse Linked List II

时间:2015-05-20 11:08:45      阅读:185      评论:0      收藏:0      [点我收藏+]

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;
	}

 

Java for LeetCode 092 Reverse Linked List II

原文:http://www.cnblogs.com/tonyluis/p/4516613.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!