public class ReverseNode {
public static void main(String[] args) {
//构造链表
Node head = new Node(0);
Node node1 = new Node(1);
Node node2 = new Node(2);
Node node3 = new Node(3);
Node node4 = new Node(4);
head.next = node1;
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = null;
//打印反转前的链表
Node h = head;
while (h != null) {
System.out.print(h.data + " ");
h = h.next;
}
System.out.println();
System.out.println("------");
//反转链表
head = reverse(head);
//打印反转后的链表
while (head != null) {
System.out.print(head.data + " ");
head = head.next;
}
}
/**
* 反转链表--递归法
*
* @param head
* @return
*/
// private static Node reverse(Node head) {
// if (head == null || head.next == null) {
// return head;
// }
// //reHead是反转后的链表的头结点
// Node reHead = reverse(head.next);
// //反转
// head.next.next = head;
// head.next = null;
// return reHead;
// }
/**
* 反转单链表--遍历法
*
* @param head
* @return
*/
private static Node reverse(Node head) {
// Node pre = head;
// Node cur = head.next;
// Node tmp = null;
// while (cur != null) {
// //缓存当前节点的指针域(即下一个节点)
// tmp = cur.next;
// //反转当前节点
// cur.next = pre;
// //后移节点
// pre = cur;
// cur = tmp;
// }
// //头结点的指针域置空
// head.next = null;
// return pre;
//更为高效的写法
if (head == null) {
return null;
}
Node node = head.next;
//将头结点置空
head.next = null;
while (node != null) {
Node nextNode = node.next;
//反转当前节点
node.next = head;
//后移元素
head = node;
node = nextNode;
}
return head;
}
static class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
}
}
}