反转链表(Java实现)

剑指offer面试题16



牛客网测试地址:https://www.nowcoder.com/questionTerminal/75e878df47f24fdc9dc3e400ec6058ca

public class Solution {
	public ListNode ReverseList(ListNode head) {
		//如果输入节点为空,返回空
		if (head == null)
			return null;
		//需要设置三个指针,分别对应当前节点前1,当前节点,当前节点后1
		ListNode preNode = null;
		ListNode inNode = head;
		ListNode nextNode = null;
		while (true) {
			nextNode = inNode.next;
			inNode.next = preNode;
			if (nextNode != null) {
				preNode = inNode;
				inNode = nextNode;
				nextNode = nextNode.next;
			} else {
				break;
			}
		}
		return inNode;
	}
}
/*
 * 节点类
 */
class ListNode {
	int val;
	ListNode next = null;

	ListNode(int val) {
		this.val = val;
	}
}







你可能感兴趣的:(剑指offer(Java实现))