链表有序链表中移除重复项
Posted jiangyi-uestc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了链表有序链表中移除重复项相关的知识,希望对你有一定的参考价值。
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 = new Node(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 = new Node(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 }
以上是关于链表有序链表中移除重复项的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 82 Remove Duplicates from Sorted List II(从已排序链表中移除重复元素)(Linked List)(*)