单链表Java实现讲解_单链表操作java实现

目标:

实现单链表的增删改查,克隆复制,容量计算,是否为空判断.

结点类

public class Node {

T data;

Node next=null;

public Node(T data)

{

this.data=data;

}

public Node()

{

}

}

链表类

public class LinkedList {

Node header=null;

//每次增加节点在表头后

public void add(T value)

{

Node node1=new Node(value);

if (header==null)

{

header=new Node();

header.next=node1;

}

else {

node1.next=header.next;

header.next=node1;

}

}

//在某个点插入

public void add(T value,int index)

{

Node node1=new Node(value);

if (header==null)

{

if(index==1)

{

header=new Node();

header.next=node1;

}

}

else {

Node p=header.next;

Node prep=header;

int i=0;

while(p!=null)

{

i++;

if (i==index)

{

node1.next=p;

prep.next=node1;

}

prep=p;

p=p.next;

}

}

}

public boolean contains(T value)

{

if (header==null)

return false;

Node p=header.next;

while (p!=null)

{

if (p.data.equals(value))

return true;

p=p.next;

}

return false;

}

public boolean remove (T value)

{

if (header==null)

return false;

Node p=header.next;

Node prep=header;

while (p!=null)

{

if (p.data.equals(value))

{

prep.next=p.next;

p.next=null;

return true;

}

prep=p;

p=p.next;

}

return false;

}

public Node getNode(int index)

{

if (header==null)

return null;

Node p=header.next;

int i=1;

while (p!=null)

{

if (i==index)

{

return p;

}

p=p.next;

i++;

}

return null;

}

public T getElement(int index)

{

if (header==null)

return null;

Node p=header.next;

int i=1;

while (p!=null)

{

if (i==index)

{

return p.data;

}

p=p.next;

i++;

}

return null;

}

public boolean isEmpty()

{

if (header==null)

return true;

return false;

}

public int size()

{

if (header==null)

return 0;

Node p=header.next;

int i=0;

while (p!=null)

{

i++;

p=p.next;

}

return i;

}

public LinkedList clonelist()

{

if (header==null)

return null;

LinkedList lk=new LinkedList();

Node header1=new Node();

lk.header=header1;

//链表第一个数据结点先行创建

Node p=header.next;

Node p1=new Node();

p1.next=null;

p1.data=p.data;

header1.next=p1;

Node prep1=null;

while (true)

{

p=p.next;

if (p==null)

break;

prep1=p1;

p1=new Node();

p1.next=null;

p1.data=p.data;

prep1.next=p1;

}

return lk;

}

}

public class Test {

public static void main(String[] args)

{

LinkedList lk1=new LinkedList();

lk1.add("aa");

lk1.add("bb");

lk1.add("cc");

lk1.add("dd");

lk1.add("ee",3);

System.out.println(lk1.contains("xx"));

System.out.println(lk1.size());

System.out.println(lk1.getElement(3));

LinkedList lk2=lk1.clonelist();

System.out.println(lk2.contains("xx"));

System.out.println(lk2.size());

System.out.println(lk2.getElement(1));

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值