您当前的位置: 首页 >  链表
  • 0浏览

    0关注

    674博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

链表洗牌

沙漠一只雕得儿得儿 发布时间:2016-11-17 19:15:32 ,浏览量:0

package 链表下;

public class reorderList {
	public static int lengthOfList(ListNode head) {
		ListNode p = head;
		int n = 0;
		while (p != null) {
			p = p.next;
			n++;
		}
		return n;
	}

	public static ListNode reverseList(ListNode head) {
		ListNode pre = head;
		ListNode p = pre.next;
		ListNode next;
		while (p != null) {
			next = p.next;
			p.next = pre;
			pre = p;
			p = next;
		}
		head.next = null;
		return pre;
	}

	public static void reorderList(ListNode head) {
		int n = lengthOfList(head);
		int half = n / 2;
		if (n % 2 != 0) {
			half++;
		}
		ListNode leftEnd = head;
		for (int i = 1; i < half; i++) {
			leftEnd = leftEnd.next; // 左半边链表的尾节点
		}
		ListNode rightStart = leftEnd.next; // 右半边链表的开始节点
		rightStart = reverseList(rightStart);// 反转右边的节点,为洗牌做准备
		leftEnd.next = null;
		ListNode left = head;
		ListNode right = rightStart;
		boolean flag = true;
		ListNode next = null;
		while (right != null) {
			if (flag) {
				next = left.next;
				left.next = right;
				left = next;
			} else {
				next = right.next;
				right.next = left;
				right = next;
			}
			flag = !flag;
		}
	}

	public static void main(String[] args) {
		int[] array = { 1, 2, 3, 4, 5, 6 };
		ListNode head = ListNode.arrayToList(array);
		reorderList(head);
		ListNode.printList(head);
	}
}
关注
打赏
1657159701
查看更多评论
立即登录/注册

微信扫码登录

0.0387s