算法 删除单链表中重复元素

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?

package com;

public class Test {

	private static class LinkedListNode {
		private char c;
		private LinkedListNode next;
		LinkedListNode(char c){
			this.c = c;
		}
		public String toString(){
			return c + (next != null ? next.toString() : "");
		}
	}

	public static void deletdDup2(LinkedListNode head) {
		LinkedListNode i = head.next;
		LinkedListNode p = head;
		LinkedListNode j;
		for (; i != null; i = i.next) {
			for (j = head;j != i; j = j.next) {
				if (i.c == j.c) {
					p.next = i.next;
					break;
				}
			}
			if(i == j){
				p = p.next;
			}
		}
	}

	public static void main(String[] args) {
		LinkedListNode one = new LinkedListNode('a');
		LinkedListNode two = new LinkedListNode('b');
		LinkedListNode three = new LinkedListNode('c');
		LinkedListNode four = new LinkedListNode('a');
		LinkedListNode five = new LinkedListNode('c');
		LinkedListNode six = new LinkedListNode('d');
		LinkedListNode seven = new LinkedListNode('b');
		LinkedListNode eight = new LinkedListNode('a');
		one.next = two;
		two.next = three;
		three.next = four;
		four.next = five;
		five.next = six;
		six.next = seven;
		seven.next = eight;
		eight.next = null;
		System.out.println(one);
		deletdDup2(one);
		System.out.println(one);
	}

}

  

posted on 2013-03-23 11:17  waxili  阅读(243)  评论(0编辑  收藏  举报

导航