java数据结构链表的实现

节点类
public class ListNode {
Object val;
ListNode next;
ListNode pre;
ListNode(int val) {
// TODO Auto-generated constructor stub
this.val = val;
}
public void display(){
System.out.println(val  + " ");
}
}
实现节点的增删该查
package data;


public class SingleList {
ListNode first;
int index = 0;
public SingleList() {
// TODO Auto-generated constructor stub
this.first=null;
}
void ListEmpty(SingleList a){
first.val = null;
first.next = first;

}

/**
*  插入一个头节点  
* @param a
*/
    public void addFirstNode(int a) {  
         ListNode node = new ListNode(a);  
         node.next = first;  
          first = node;  
    }  
/**
* 直接从最后开始添加元素
* @param c
*/
void AddListNodeEnd(int c){
ListNode node = new ListNode(c);
ListNode current = first;
while(current.next!=null){
current = current.next;
}
current.next = node;
}
/**
* 在a的位置添加一个元素C
* @param c
* @return
*/
ListNode AddListNode(int a,int c){
ListNode node = new ListNode(c);
ListNode preNode = first;
ListNode current = first;
while(index != a){
preNode = current;
current = current.next;
index ++;
}
if(preNode == current){
node.next = first;
first = node;
}else{
node.next = current;
preNode.next = node;
}
index = 0;
return node;
}
/**
* 删除位置a的节点
* @param a
* @return
*/
ListNode DeletNode(int a){
ListNode preNode = first;
ListNode current = first;
while(index !=a){
preNode = current;
current = current.next;
index++;
}
if(current == first){
first = first.next;
}else{
preNode.next = current.next;
index = 0;
}
return current;
}


/**
* 查找在位置a的节点
* @param a
* @return
*/
ListNode IndexNode(int a){
ListNode current = first;
while(index !=a){
current = current.next;
index++;
}
return current;
}
/**
* 查找与E相同的节点
* @param e
* @return boolean
*/
boolean LocateElem(int e){
ListNode current = first;
while(current != null){
if(current.val.equals(e)){
return true;
}
current = current.next;
}
return false;
}
/**
* 显示链表中的所有节点的值
*/
void Display(){
String str = "";
ListNode current = first;
while(current != null){
str+=current.val;
current = current.next;
}
if(current == first){
str+=first.val;
}
System.out.println(str);
}
}


main函数实现其函数的调用
package data;


public class Main {
public static void main(String[] args) {
SingleList singleList = new SingleList();
singleList.addFirstNode(1);
singleList.AddListNodeEnd(4);
singleList.AddListNodeEnd(4);
singleList.AddListNodeEnd(4);
//singleList.ListEmpty(singleList);
singleList.AddListNode(0, 3);

// singleList.DeletNode(1);
System.out.println(singleList.IndexNode(1).val);

System.out.println(singleList.LocateElem(3));
singleList.Display();
}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值