public class LinkedList {
Node head;
public static void main(String[] args) {
LinkedList list=new LinkedList();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
printList(list.head);
printList(reverse(list.head));
}
//头插法建立链表,头节点不为空
public void add(int num) {
Node node = new Node(num);
if (this.head == null) {
this.head = node;
} else {
node.next = this.head;
this.head = node;
}
}
//链表反转
public static Node reverse(Node head) {
Node pre = null;
Node next = null;
while (head != null) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
public static void printList(Node p) {
while(p != null){
System.out.printf("%d ",p.val);
p = p.next;
}
System.out.println();
}
}
class Node {
int val;
Node next = null;
public Node() {
}
public Node(int val) {
this.val = val;
}
}
输出:
稍微解释一下过程:
第一次循环:
head=1 1.next=null
第二次循环:
head=2 2.next=1
第三次循环:
head=3 3.next=2
第四次循环:
head=4 4.next=3
第五次循环:
head=5 5.next=4
是不是就串起来了呀。最后一次循环pre=5,成为新的头结点。