Reverse LinkedList (I, II)

8 篇文章 0 订阅

反转列表I,Java实现如下:


	public static Node reverse(Node root) {
		Node head = null;
		Node next = null;
		Node curr = root;
		while (curr != null) {
			next = curr.next;
			if (head == null) {
				head = curr;
				head.next = null;
			} else {
				curr.next = head;
				head = curr;
			}
			curr = next;
		}

		return head;
	}

	private static class Node {
		int val;
		Node next;

		public Node(int val, Node next) {
			this.val = val;
			this.next = next;
		}

		public Node(int val) {
			this(val, null);
		}
	}

反转列表II,反转给定区域的列表。

例如,给定{1, 2, 3, 4, 5} ,反转第2个到第4个之间的所有元素为{1,4,3, 2, 5}。

解题思路如上,然需要小心不同越界。


public static Node reverse(Node root, int m, int n) {
		if (root == null || m < 1 || n < m || size(root) < n)
			throw new IllegalArgumentException(
					"empty root or m < 1 or n < m or n > size(list)");

		Node dumy = new Node(-1, root);
		Node pre = dumy;
		for (int i = 0; i < m - 1; i++) {
			pre = pre.next;
		} // the node right before the m-th node

		Node head = null; // head for reverse
		Node curr = pre.next;
		Node tail = curr;
		Node next = null;
		for (int i = m; i <= n; i++) {
			next = curr.next;
			curr.next = head;
			head = curr;
			curr = next;
		}
		pre.next = head;
		tail.next = curr; //attach the elements after n-th element
		return dumy.next;
	}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值