package demo6; /** * java反轉單向鏈表方法 * @author mengfeiyang * */ public class LinkReverse2 { public static void main(String[] args) { /**鏈表構造*/ Node node1 = new Node(1); Node node2 = new Node(2); Node node3 = new Node(3); Node node4 = new Node(4); Node node5 = new Node(5); node1.next = node2; node2.next = node3; node3.next = node4; node4.next = node5; show(node1); System.out.println("反轉過程:"); Node head = reverse(node1);//反轉 System.out.println("反轉後:"); show(head); } static void show(Node head){ while(head != null){ System.out.print(head.val+">"); head = head.next; } } public static Node reverse(Node head){ Node cur = head; Node post = head.next; head.next = null; show(cur); System.out.println(); while(post!=null){ //初始:cur=1 Node tmp = post; //首次迭代:tmp = 2,第二次:tmp=3,第三次:tmp=4; post = post.next; //post = 3,第二次:post=4,第三次:post=5 tmp.next = cur; //2>1,第二次:3>2>1,第三次:4>3>2>1 cur = tmp; //鏈表結構:2>1,第二次:3>2>1,第三次:4>3>2>1 show(cur); System.out.println(); } return cur; } static class Node{ int val; Node next; Node(int val){ this.val = val; //this.next = null; } } }
執行過程及結果:java
1>2>3>4>5>反轉過程:
1>
2>1>
3>2>1>
4>3>2>1>
5>4>3>2>1>
反轉後:
5>4>3>2>1>node