Java實(shí)現(xiàn)單鏈表反轉(zhuǎn),遞歸和非遞歸兩種形式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
|
/** * 反轉(zhuǎn)單鏈表 */ /** * 定義鏈表 * * @author 16026 * */ class Node { int val; Node next; public Node( int val) { this .val = val; } } public class ReverseList { /** * 反轉(zhuǎn)鏈表 * * @param head * @return */ public static Node reverseList(Node head) { if (head == null || head.next == null ) { return head; } Node reHead = null ; // 定義新鏈表頭結(jié)點(diǎn) while (head != null ) { Node cur = head.next; // 記錄下一個(gè)節(jié)點(diǎn) head.next = reHead; // 將rehead節(jié)點(diǎn)連接到head節(jié)點(diǎn)上 reHead = head; // 讓rehead指向head head = cur; // 將head指向下一個(gè)節(jié)點(diǎn) } return reHead; } /** * 遞歸反轉(zhuǎn)鏈表 * * @param head * @return */ public static Node reverseList2(Node head) { if (head == null || head.next == null ) return head; Node rehead = reverseList2(head.next); head.next.next = head; // 將頭節(jié)點(diǎn)置于末端 head.next = null ; // 防止鏈表循環(huán) return rehead; } /** * 打印鏈表 * * @param head */ public static void printList(Node head) { if (head == null ) return ; while (head != null ) { System.out.print(head.val + " " ); head = head.next; } } /** * 測(cè)試 * * @param args */ public static void main(String[] args) { Node n1 = new Node( 1 ); Node n2 = new Node( 2 ); Node n3 = new Node( 3 ); Node n4 = new Node( 4 ); Node n5 = new Node( 5 ); n1.next = n2; n2.next = n3; n3.next = n4; n4.next = n5; // Node rehead = reverseList(n1); Node rehead = reverseList2(n1); printList(rehead); } } |
運(yùn)行結(jié)果如下:
以上所述是小編給大家介紹的Java實(shí)現(xiàn)單鏈表翻轉(zhuǎn)實(shí)例代碼,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)服務(wù)器之家網(wǎng)站的支持!
原文鏈接:http://blog.csdn.net/qq_21150865/article/details/65629749