連結串列設計
阿新 • • 發佈:2021-06-28
單鏈表:單指向連結串列
雙向連結串列:前後都指向連結串列
題目1:單鏈表和雙向連結串列如何反轉
package day2; //反轉連結串列 public class Code01_ReverseList { public static class Node { public int value; public Node next; public Node(int value,Node next) { this.value = value; this.next = next; } } public static class DoubleNode { public int value; public DoubleNode last; public DoubleNode next; public DoubleNode(int data) { value = data; } } // 反轉單鏈表 public static Node reverseLinkedList(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 DoubleNode reverseDoubleList(DoubleNode head) { DoubleNode pre = null; DoubleNode next = null; while(head != null) { next = head.next; head.next = pre; head.next = next; pre = head; head = next; } return pre; } }
題目2:把給定值都刪除
package day2; //刪除連結串列中的一個元素 import day2.Code01_ReverseList.Node; public class Code02_DeleteGivenValue { public static class Node { public int value; public Node next; public Node(int value,Node next) { this.value = value; this.next = next; } } public static Node removeValue(Node head,int num) { while(head != null) { if(head.value != num) { break; } head = head.next; } //head來到第一個不需要刪的位置 Node pre = head; Node cur = head; // while(cur != null) { if(cur.value == num) { pre.next = cur.next; } else { pre = cur; } cur = cur.next; } return head; } }