链表逆序的思想:
1)遍历链表中的节点,放入栈中,然后进行出栈的操作,即可得到逆序的链表;
2)将链表中的元素,存入数组或者队列或者有序集合中,然后逆序去读元素,重新链接成链表;
3)通过交换链表中的元素,从而实现逆序。可以这么理解——顺序移除链表中的头节点,作为头节点添加到新链表。即逐个遍历原链表中的节点,作为新链表的头节点,插入。
前两种方法比较简单,这里说下第三种方法。代码如下:
step1,构建节点
static class Node {
private int value;
private Node next;
public Node(int value, Node next) {
this.value = value;
this.next = next;
}
public int getValue() {
return value;
}
public Node setValue(int value) {
this.value = value;
return this;
}
public Node getNext() {
return next;
}
public Node setNext(Node next) {
this.next = next;
return this;
}
public boolean hasNext() {
return next != null;
}
}
step2,初始化链表
/**
* 构建一个链表
*
* @return 链表头节点
*/
private static Node initLink() {
//头节点
Node head = null;
//当前节点
Node cur = null;
for (int i = 0; i < 10; i++) {
if (cur == null) {
cur = head = new Node(i, null);
continue;
}
Node next = new Node(i, null);
cur.setNext(next);
cur = next;
}
return head;
}
step3,打印链表
/**
* 遍历链表
*
* @param head head node
*/
private static void printLink(Node head) {
Node node = head;
while (node != null) {
System.out.print(node.value + "->");
node = node.next;
}
System.out.println();
}
step4,逆序
/**
* 链表逆序
*
* @param headOld ori link head node
* @return new link head node
*/
private static Node reverseLink(Node headOld) {
Node head = headOld;
Node next = head.next;
while (next != null) {
Node cur = next;
next = next.next;
if (head == headOld) {
head.next = null;
}
cur.next = head;
head = cur;
}
return head;
}
最后一步,运行
public static void main(String[] args) {
System.out.println("初始化链表:");
Node headOri = initLink();
printLink(headOri);
System.out.println("逆序后链表:");
Node headNew = reverseLink(headOri);
printLink(headNew);
//打印结果
//初始化链表:
//0->1->2->3->4->5->6->7->8->9->
//逆序后链表:
//9->8->7->6->5->4->3->2->1->0->
}