码迷,mamicode.com
首页 > 其他好文 > 详细

Remove duplicate in single linkedlist

时间:2014-10-20 21:21:04      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   java   for   sp   div   

  1/* 1.Node.java*/
  2 package Chapter2;
  3  
  4 public class Node<T> {  //T可以是int,string等
  5 public T data;
  6 public Node<T> next;
  7 public Node(T d, Node<T> n){
  8 data = d;
  9 next = n;
 10 }
 11 }
 12 
 13 /*2.MyLinkedList.java*/
 14 
 15 package Chapter2;
 16  
 17 //Singly Linked List
 18 public class MyLinkedList<T> {
 19 public Node<T> head;
 20  
 21 public MyLinkedList(Node<T> h) {//构造函数没有返回值
 22 head = h;
 23 }
 24  
 25 public MyLinkedList(T[] dataArray) {//一个类可以有多个构造函数
 26 if (dataArray == null || dataArray.length <= 0)
 27 return;
 28 head = new Node<>(dataArray[0], null);
 29 Node<T> node = head;//node指向head
 30 for (int i = 1; i < dataArray.length; i++) {
 31 node.next = new Node<T>(dataArray[i], null);
 32 node = node.next;
 33 }
 34 }
 35  
 36 public void print() {
 37 Node<T> cur = head;
 38 while (cur != null) {
 39 System.out.print(cur.data);
 40 if (cur.next != null) {
 41 System.out.print(" -> ");
 42 }
 43 cur = cur.next;
 44 }
 45 System.out.println();
 46 }
 47 }
 48 
 49 /*3.RemoveDuplication.java*/
 50 package Chapter2;
 51  
 52 import java.util.HashSet;
 53  
 54 public class RemoveDuplication {
 55 public static <T> void removeDup(MyLinkedList<T> list) {//为什么要加T?不是void吗?A:固定句型
 56 if (list == null || list.head == null)
 57 return;
 58  
 59 HashSet<T> hashSet = new HashSet<>();
 60 Node<T> prev = list.head;
 61 Node<T> cur = list.head.next;
 62 hashSet.add(list.head.data);
 63  
 64 while (cur != null) {
 65 if (hashSet.contains(cur.data)) {
 66 prev.next = cur.next;
 67 cur.next = null;
 68 cur = prev.next;
 69 } else {
 70 hashSet.add(cur.data);
 71 prev = cur;
 72 cur = cur.next;//更新cur为下一次循环做准备
 73 }
 74 }
 75 }
 76 
 77 public static <T> void removeDupNoBuf(MyLinkedList<T> list) {
 78 if (list == null || list.head == null)
 79 return;
 80 Node<T> start = list.head;
 81 while (start != null) {
 82 Node<T> prev = start;
 83 Node<T> cur = start.next;
 84 while (cur != null) {
 85 if (cur.data == start.data || cur.data == prev.data) {
 86 prev.next = cur.next;
 87 cur.next = null;
 88 cur = prev.next;
 89 } else {
 90 prev = cur;
 91 cur = cur.next;
 92 }
 93 }
 94 start = start.next;
 95 }
 96 }
 97  
 98 public static void main(String[] args) {
 99 MyLinkedList<Integer> list = new MyLinkedList<>(new Integer[] { 2, 7, 5, 4, 2, 2, 4, 6 });
100 list.print();
101 removeDup(list);
102 list.print();
103 }
104 }

 

Remove duplicate in single linkedlist

标签:style   blog   color   io   ar   java   for   sp   div   

原文地址:http://www.cnblogs.com/tonychiang/p/4038521.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!