数据结构:
1.2 链表:
实现单链表,支持增删操作
public class MyLinkList {
private int size;
private Node head;
private class Node{
private Node next;
private Object data;
Node(Object data){
this.data=data;
}
}
public Object add(Object data) {
Node newNode = new Node(data);
if (size==0) {
head=newNode;
}else {
newNode.next=head;
head=newNode;
}
size++;
return data;
}
public boolean remove(Object data) {
Node currentNode=head;
Node perviousNode=head;
if (size==0) {
return false;
}
while (currentNode.next!=null) {
perviousNode=currentNode;
currentNode=currentNode.next;
if (currentNode.data==data) {
if (currentNode==head) {
head=currentNode.next;
}else {
perviousNode.next=currentNode.next;
}
size--;
return true;
}
}
return false;
}
@Override
public String toString() {
// TODO Auto-generated method stub
String result="";
for (int i = 0; i < size; i++) {
result+=","+head.data;
head=head.next;
}
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
//实现单链表,支持增删操作
MyLinkList list=new MyLinkList();
list.add(5);
list.add(8);
list.add(56);
list.add(4);
list.remove(56);
System.out.println(list.toString());
}
}
实现双向链表,支持增删操作
public class DoubleLinkList {
private int size;
private Node head;
private Node tail;
private class Node{
private Node pervious;
private Node next;
private Object data;
Node(Object data,Node pNode, Node nNode){
this.data=data;
this.pervious=pNode;
this.next=nNode;
}
}
DoubleLinkList(){
size=0;
head=null;
tail=null;
}
DoubleLinkList(Object data){
head=new Node(data,null,null);
tail=head;
size++;
}
public Object addhead(Object data) {
Node newNode=new Node(data,null,head);
if (size==0) {
head=newNode;
tail=newNode;
}else {
newNode.next=head;
head=newNode;
}
size++;
return data;
}
public Object addTail(Object data) {
Node newNode=new Node(data,null,tail);
if (size==0) {
head=newNode;
tail=newNode;
}else {
tail.pervious=newNode;
}
size++;
return data;
}
public boolean remove(Object data) {
Node currentNode=head;
Node perviousNode=head;
if (size==0) {
return false;
}
while (currentNode.next!=null) {
perviousNode=currentNode;
currentNode=currentNode.next;
if (currentNode.data==data) {
if (currentNode==head) {
head=currentNode.next;
}else {
perviousNode.next=currentNode.next;
}
size--;
return true;
}
}
return false;
}
@Override
public String toString() {
// TODO Auto-generated method stub
String result="";
for (int i = 0; i < size; i++) {
result+=","+head.data;
head=head.next;
}
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
//实现双向链表,支持增删操作
DoubleLinkList list=new DoubleLinkList();
list.addhead(5);
list.addhead(8);
list.addhead(56);
list.addhead(4);
System.out.println(list.toString());
}
}