您的位置:首页 > 其它

LeetCode 143 Reorder List

2014-06-21 09:34 357 查看
Given a singly linked list L: L0→L1→…→Ln-1→Ln,

reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…

You must do this in-place without altering the nodes' values.

For example,

Given
{1,2,3,4}
, reorder it to
{1,4,2,3}
.

public class Solution {
	public ListNode inverseList(ListNode head) {
		if (head == null || head.next == null)
			return head;
		ListNode dumny = new ListNode(-1);
		ListNode p = head;
		ListNode cur;
		while (p != null) {
			cur = p;
			p = p.next;
			cur.next = dumny.next;
			dumny.next = cur;
		}
		return dumny.next;
	}

	public void reorderList(ListNode head) {
		if (head == null || head.next == null || head.next.next == null)
			return;
		ListNode p = head;
		ListNode q = head;
		ListNode tmp = null;
		while (q != null) {
			tmp = p;
			p = p.next;
			if (q.next != null)
				q = q.next.next;
			else {// 注意要将前面的部分和后面要逆置的部分要断开
				tmp.next = null;// 链表总长度为奇数时,断开
				break;
			}
			if (q == null)
				tmp.next = null;// 链表总长度为偶数时,断开
		}
		q = inverseList(p);
		p = head;
		while (p != null && q != null) {
			tmp = q.next;
			q.next = p.next;
			p.next = q;
			q = tmp;
			p = p.next.next;
		}
	}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: