Skip to content

Commit

Permalink
链表集合set
Browse files Browse the repository at this point in the history
  • Loading branch information
Xikl committed Nov 12, 2018
1 parent db41978 commit afc9ee9
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/main/java/com/ximo/datastructuresinaction/list/LinkedList.java
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,30 @@ public E remveLast() {
return remove(size - 1);
}

/**
* 删除指定元素
* 只能删除一个
*
* @param e 被删除的元素
*/
public void removeElement(E e) {
Node prev = dummyHead;
while (prev.next != null) {
if (prev.next.e.equals(e)) {
break;
}
// 后移一位
prev = prev.next;
}
if (prev.next != null) {
Node delNode = prev.next;
prev.next = delNode.next;
// help gc
delNode.next = null;
size--;
}
}

@Override
public String toString() {
StringBuilder res = new StringBuilder();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package com.ximo.datastructuresinaction.set;

import com.ximo.datastructuresinaction.list.LinkedList;

/**
* @author Ximo
* @date 2018/11/12 21:50
*/
public class LinkedListSet<E> implements Set<E> {

private LinkedList<E> linkedList;

public LinkedListSet() {
this.linkedList = new LinkedList<>();
}

@Override
public void add(E e) {
if (!linkedList.contains(e)) {
linkedList.addFirst(e);
}
}

@Override
public void remove(E e) {
linkedList.removeElement(e);
}

@Override
public boolean contains(E e) {
return linkedList.contains(e);
}

@Override
public int getSize() {
return linkedList.getSize();
}

@Override
public boolean isEmpty() {
return linkedList.isEmpty();
}
}

0 comments on commit afc9ee9

Please sign in to comment.