剑指offer面试题16-反转链表

题目:

定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。

链表结构如下

package com.aii.algorithm;

public class Node {
	int value;
	Node next;

	public Node(int value) {
		this.value = value;
	}

	@Override
	public String toString() {
		return "Node [value=" + value + ", next=" + next + "]";
	}

}


保证链表不断是关键,用临时变量记录一些值。


package com.aii.algorithm;

public class ReverseLinkedList {
	/**
	 * @return 返回倒转以后的链表的头
	 * */
	public Node reverse(Node head) {
		if (head == null) {
			throw new RuntimeException();
		}
		if (head.next == null) {
			return head;
		}

		Node current = head;
		Node preNode = null;
		while (current != null && current.next != null) {
			// 先记录当前的下一个是谁
			Node next = current.next;
			// 然后改变当前的下一个,既然反转,也就是指向前一个
			current.next = preNode;

			// 这些处理完了,做好后续工作,以便下一次循环,记录当前的pre
			preNode = current;
			// 往后走一个
			current = next;
		}
		// 由于current,next=null的时候即跳出循环,这个时候current为最后一个元素。他的next是null的
		// 所以要执行此步,让第一个元素的next指向pre
		current.next = preNode;
		// 现在头是尾了,把他的头断掉
		head.next = null;
		return current;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值