企業(yè)建站技術(shù)軟文營銷名詞解釋
鏈表的定義,相信大家都知道,這里就不贅述了只是鏈表分單向鏈表和雙向鏈表,廢話不多說,直接上代碼
鏈表節(jié)點的定義:
public class Node {int val;Node next;Node pre;public Node(int val, Node next, Node pre) {this.val = val;this.next = next;this.pre = pre;}public Node(int val, Node next) {this.val = val;this.next = next;}public Node(int val) {this.val = val;}public Node() {}
}
打印鏈表的兩種方式:
//從前往后打印鏈表private void print(Node head) {while (head != null) {System.err.print(head.val);head = head.next;}System.err.println();}//從后往前打印鏈表private void print1(Node head) {while (head != null) {System.err.print(head.val);head = head.pre;}System.err.println();}
翻轉(zhuǎn)單向鏈表:核心思路是先斷開連接,再將next指向前繼節(jié)點,為了避免斷開之后,找不到前繼節(jié)點,需要用一個臨時變量記錄前繼節(jié)點,在下一輪循環(huán)的時候把當(dāng)前節(jié)點的next指向上一輪循環(huán)時的pre
//翻轉(zhuǎn)單鏈表private Node reverList(Node head) {Node pre = null;Node next = null;while (head != null) {//下一次進(jìn)來的時候連上前一個節(jié)點,先記錄下前一個節(jié)點,不能先斷開了后面的節(jié)點,不然就找不到了next = head.next;head.next = pre;pre = head;head = next;}return pre;}@Testpublic void reverList() {Node one = new Node(2, new Node(3, new Node(4)));print(one);print(reverList(one));}
翻轉(zhuǎn)雙向鏈表:思路同單向鏈表一樣,只是多了一些判斷
//翻轉(zhuǎn)雙向鏈表private Node reverseDoubleList(Node head) {Node next = null;Node pre = null;while (head != null) {next = head.next;head.next = pre;head.pre = next;pre = head;head = next;}return pre;}@Testpublic void reverseDoubleList() {Node one = new Node(1);Node two = new Node(2);Node three = new Node(3);one.next = two;one.pre = null;two.next = three;two.pre = one;three.pre = two;three.next = null;print(one);print1(three);Node node = reverseDoubleList(one);print(node);print1(one);}
從鏈表中刪除指定的數(shù)據(jù):
//從單鏈表中刪除指定的數(shù)據(jù)private Node removeList(Node head, int target) {Node pre = null;Node next = null;while (head != null) {//第一輪循環(huán)找到新的頭結(jié)點,因為要刪除的數(shù)據(jù)可能是第一個也可能是最后一個next = head.next;if (target != head.val) {break;}head = next;}next = pre = head;//while (next != null) {if (target == next.val) {next = next.next;pre.next = next;//相等的時候提前把pre和下一個連起來,這樣下一個如果相等,只需要移動pre即可continue;}pre = next;//不相等的時候pre記錄前一個節(jié)點,等到下一輪如果相等時候就可以把pre和next連上了next = next.next;}return head;}@Testpublic void removeList() {Node one = new Node(2, new Node(5, new Node(2, new Node(3, new Node(2)))));print(one);print(removeList(one, 2));}