題目:定義一個函數,輸入一個鏈表的頭結點,反轉該鏈表並輸出反轉後的鏈表的頭結點。
解題思路:單向鏈表只能實現單向遍歷,改變鏈表方向就是要把當前鏈表的節點指向它的前一個節點,
一旦當前鏈表指向發生了變化,就不能根據此節點獲取到它後面的節點,因此在改變方向前要保存當前節點的下一節點,防止鏈表斷開,
所以須要三個指針來保存當前節點,當前節點的前節點,當前節點的下節點。node
注意:若是當前節點沒有下一節點,則此節點就是反轉後的鏈表的頭結點。
函數
另一種解決辦法是使用一個棧結構,順序遍歷鏈表,把每一個節點依次入棧。待所有節點入棧後,依次把節點從棧中取出並鏈接,這樣獲得的鏈表也是反轉後的鏈表。this
1 package Solution; 2 3 4 public class No16ReverseList { 5 6 public static class ListNode { 7 int data; 8 ListNode next; 9 10 public ListNode() { 11 12 } 13 14 public ListNode(int value, ListNode next) { 15 this.data = value; 16 this.next = next; 17 } 18 } 19 20 public static ListNode reverseList(ListNode head) { 21 if (head == null) 22 throw new RuntimeException("invalid List,can't be null"); 23 if (head.next == null) 24 return head; 25 ListNode reversedHead = null; 26 ListNode node = head; 27 ListNode preNode = null; 28 while (node != null) { 29 ListNode nextNode = node.next; 30 if (nextNode == null) 31 reversedHead = node; 32 // 賦值順序不能變 33 node.next = preNode; 34 preNode = node; 35 node = nextNode; 36 } 37 return reversedHead; 38 } 39 40 public static void print(ListNode head) { 41 if (head == null) 42 System.out.println("當前鏈表爲空"); 43 while (head != null) { 44 System.out.print(head.data + ","); 45 head = head.next; 46 } 47 } 48 49 public static void main(String[] args) { 50 ListNode node1 = new ListNode(4, null); 51 ListNode node2 = new ListNode(3, node1); 52 ListNode node3 = new ListNode(2, node2); 53 ListNode node4 = new ListNode(1, node3); 54 55 print(reverseList(node4)); 56 System.out.println(); 57 print(reverseList(new ListNode(5, null))); 58 System.out.println(); 59 print(reverseList(new ListNode())); 60 System.out.println(); 61 } 62 63 }