連結串列去重原理示意圖
阿新 • • 發佈:2018-12-18
package interview.datastructure; import java.util.Hashtable; /** * 實現連結串列的插入和刪除結點的操作 */ public class Link_list { //定義一個結點 class Node { Node next = null; int date; public Node(int date) { this.date = date; } } Node head = null; public void addNode(int d) { Node newNode = new Node(d); if (head == null) { head = newNode; return; } Node temp = head; //迴圈遍歷到連結串列的尾部,將資料結點插入到連結串列的尾部 while (temp.next != null) { temp = temp.next; } temp.next = newNode; } //刪除結點 public Boolean deleteNode(int index) { if (index < 1 || index > length()) return false; if (index == 1) { head = head.next; return true; } int i = 2; Node preNode = head; Node curNode = preNode.next; while (curNode != null) { if (i == index) { preNode.next = curNode.next; return true; } preNode = curNode; curNode = curNode.next; i++; } return true; } public int length() { int length = 0; Node temp = head; while (temp != null) { length++; temp = temp.next; } return length; } //氣泡排序已經改變了原來的連結串列的結構 public Node orderList() { Node nextNode = null; int temp = 0; Node curNode = head; while (curNode.next != null) { nextNode = curNode.next; while (nextNode != null) { if (curNode.date > nextNode.date) { temp = curNode.date; curNode.date = nextNode.date; nextNode.date = temp; } nextNode = nextNode.next; } curNode = curNode.next; } return head; } public void printList() { Node temp = head; while (temp != null) { System.out.println(temp.date); temp = temp.next; } } public static void main(String[] args) { Link_list lik = new Link_list(); lik.addNode(3); lik.addNode(2); lik.addNode(1); lik.addNode(6); lik.addNode(2); System.out.println(lik.length()); System.out.println("排序前:"); lik.printList(); // System.out.println("排序後:"); lik.orderList(); lik.printList(); lik.deleteDuplecate(); System.out.println("去重後:"); lik.printList(); } //連結串列去重 public void deleteDuplecate() { Hashtable<Integer, Integer> table = new Hashtable<>(); Node temp = head; Node pre = null; while (temp != null) { if (table.containsKey(temp.date)) { pre.next = temp.next; System.out.println(pre.date+"\t125"); } else { table.put(temp.date, 1); pre = temp; } temp = temp.next; } }}