Created
June 18, 2014 16:31
-
-
Save chouclee/fddce83f4860442aa333 to your computer and use it in GitHub Desktop.
[CC150][2.1] Write code to remove duplicates from an unsorted linked list FOLLOW UP How would you solve this problem if a temporary buffer is not allowed?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.util.Random; | |
| //* without temporary buffer | |
| //* time O(N^2) | |
| public class LinkedList<Item> { | |
| private class Node { | |
| Item item; | |
| Node next; | |
| public Node(Item item) { | |
| this.item = item; | |
| this.next = null; | |
| } | |
| } | |
| private Node first; | |
| private Node last; | |
| private int N; | |
| public LinkedList() { | |
| N = 0; | |
| } | |
| public boolean isEmpty() { | |
| return N == 0; | |
| } | |
| public void add(Item item) { | |
| if (isEmpty()) { | |
| first = new Node(item); | |
| last = first; | |
| N++; | |
| } | |
| else { | |
| Node oldLast = last; | |
| last = new Node(item); | |
| oldLast.next = last; | |
| N++; | |
| } | |
| } | |
| public void removeDuplicate() { | |
| Node curr = first; | |
| if (curr == null) return; | |
| Node p, q; // p points to previous Node of q | |
| while (curr != null) { | |
| p = curr; | |
| q = curr.next; | |
| while (q != null) { | |
| if (q.item.equals(curr.item)) { | |
| p.next = q.next; // if q is same to current node, delete q, and q points to q.next | |
| q.item = null; | |
| q = q.next; | |
| } | |
| else { | |
| p = q; | |
| q = q.next; | |
| } | |
| } | |
| curr = curr.next; | |
| } | |
| } | |
| public String toString() { | |
| Node curr = first; | |
| String s = ""; | |
| while (curr != null) { | |
| s += curr.item.toString() + " "; | |
| curr = curr.next; | |
| } | |
| s += "\n"; | |
| return s; | |
| } | |
| public static void main (String[] args) { | |
| LinkedList<Integer> test = new LinkedList<Integer>(); | |
| Random rd = new Random(); | |
| for (int i = 0; i < 10; i++) { | |
| test.add(rd.nextInt(10)); | |
| } | |
| System.out.println(test.toString()); | |
| test.removeDuplicate(); | |
| System.out.println(test.toString()); | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment