题目:
定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。
链表结构如下
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;
}
}