翻转单链表在面试中经常被问到,也是最能考察对链表的认识以及操作,很经典的题目,这个问题考虑起来很简单,不就是把后一个节点的指针翻转指向前一个节点么,但是真让你徒手写代码刚开始还是会有点懵逼的,以下是代码示例,大家可以参考下。
package com.testnode;
//首先创建一个链表节点对象
class Node {
private Node next;
private int value;
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
/**
* 翻转单链表测试类
*/
public class RevertNodeTest {
//按顺序打印链表的值
public static void printNode(Node head) {
Node current = head;
while (current != null) {
System.out.println(current.getValue());
current = current.getNext();
}
}
//遍历原始连表实现翻转
public static Node revertNode(Node head) {
Node current = head;// current 用来表示当前使用的节点,当做循环的游标
Node last = null;// last 表示上一个节点
while (current != null) {
Node next = current.getNext();//暂存当前节点的下一个节点的引用给next 用来遍历原始连表
current.setNext(last);//将当前节点指针区域指向前一个节点,实现翻转
last = current;//将当前节点赋值给last
current = next;//将暂存的next赋值给current
}
return last;//last是原始连表的最后一个节点,翻转后就是新链表的头节点
}
public static void main(String[] args) {
//创建一个链表
Node node4 = new Node();
node4.setValue(4);
Node node3 = new Node();
node3.setValue(3);
node3.setNext(node4);
Node node2 = new Node();
node2.setValue(2);
node2.setNext(node3);
Node node1 = new Node();
node1.setValue(1);
node1.setNext(node2);
printNode(node1);//打印原始链表
Node node = revertNode(node1);
System.out.println("------------------");
printNode(node);//打印翻转后链表
}
}
除了这种方式还可以用递归方式来翻转,参考下一篇博客。