【連結串列】有序連結串列中移除重複項
阿新 • • 發佈:2018-12-02
1 public class Main { 2 3 public Node removeDup(Node node){ 4 5 if (node == null || node.next == null || node.next.next == null){ 6 return node; 7 } 8 9 Node pre = node.next; 10 Node cur = node.next.next; 11 12 while (cur != null){13 if (cur.data == pre.data){ 14 pre.next = cur.next; 15 }else { 16 pre = cur; 17 } 18 cur = cur.next; 19 } 20 21 return node; 22 } 23 24 25 public Node createListNodes() { 26 Node node7 = newNode(7, null); 27 Node node6 = new Node(5, node7); 28 Node node5 = new Node(5, node6); 29 Node node4 = new Node(5, node5); 30 Node node3 = new Node(3, node4); 31 Node node2 = new Node(3, node3); 32 Node node1 = new Node(1, node2); 33 Node head = newNode(0, node1); // head pointer 34 35 return head; 36 } 37 38 public static void main(String[] args) { 39 Main main = new Main(); 40 Node node = main.removeDup(main.createListNodes()); 41 42 if (node != null) { 43 node = node.next; 44 while (node != null) { 45 System.out.println(node.data); 46 node = node.next; 47 } 48 } 49 } 50 }