这个题目是之前参加面试时遇到的,题目基础要求是:给定指定节点数的单向链表,如何反转整个链表?
这个问题以前也遇到过几次,每次都是写完就忘了,这里记录下实现以备后面思考查看。
1.先自定义Node结构
class Node {
private int value;
private Node next;
public Node(int value) {
this.value = value;
}
public void setNext(Node next) {
this.next = next;
}
public Node getNext() {
return next;
}
}
2.初始化一个指定长度的单向链表
int i = 10;
Node firstNode = null;
Node lastNode = null;
while(i > 0) {
Node temp = new Node(i);
if(firstNode == null) {
firstNode = temp;
} else {
lastNode.setNext(temp);
}
lastNode = temp;
i--;
}
3.借助三个变量来实现整个单链表的反转
// Reverse this linked list
Node tailNode = null;
Node headNode = null;
Node tempNode = firstNode;
while(tempNode != null) {
// Store the next node reference
tailNode = tempNode.getNext();
if(headNode == null) {
// the first node, remove the next reference
tempNode.setNext(null);
} else {
// set now node's next reference to the new head node
tempNode.setNext(headNode);
}
// set the headNode reference to new node
headNode = tempNode;
// move the node to deal the next node
tempNode = tailNode;
}
System.out.println(headNode);