线性表之单向链表、双向链表

线性表— 链表

单向链表

public class LinkList<T>{
	private Node head;
	private int N;
	private class Node {
		T item;
		Node next;
		public Node (T item, Node next){
			this.item = item;
			this.next = next;
		}
	}
	public LinkList(){
		this.head=new Node (null,null);
		this.N = 0;
	}
	public void clear(){
		head.next = null;
		this.N = 0;
	}
	public int length(){
		return N;
	}
	public boolean isEmpty(){
		return N == 0;
	}
	
	public T get (int i){
		Node n =head.next;
		for (int index ==0 ;index <i; index++){
			n=n.next;
		}
		return n.item;
	}
//末尾添加元素
	public void insert(T t){
	//找尾节点
	  	Node n =head ;
	  	while (n.next !=null){
			n = n.next;
		}
		//创建一个新的节点
		Node newnode = new Node(t,null)
		//最后一个节点指向新接点
		n.next = newnode;
		//元素个数+1
		N++;
	}
	public void insert(int i ,T t){
		Node pre = head ;
		for (int index =0; index<=i-1:index++){
			pre =pre.next;
		}
		Node curr = pre.next;
		Node newcode =new Node(t,curr);
		pre.next = newcode;
		N++;	
	}
	public T remove(int i){
		Node pre = head ;
		for (int index =0; index<=i-1:i++){
			pre =pre.next;
		}
		Node curr = pre.next;
		Node nextNode =curr.next;
		pre.next = nextNode;
		N--;
		return curr.item;
	}
	public int indexof(T t){
		Node n =head;
		for (int i=0 ;n.next!=null;i++){
			n=n.next;
			if(n.item.equals(t)){
				return i;	
			}	
		}
		return -1;
	}
}

双向列表

//插入
//创建新的结点 让当前结的尾结点指向新的结点 新结点成为尾结点
//先判断是否为空
public void insert(T t){
	if (isEmpty()){
		Node newNode =new Node(t,head,null);
		last =newNode;
		head.Next = last;
	}else{
		New oldLast =last;
		Node newNode =new Node(t,oldlast,null);
		oldlast = newNode;
		last =newNode ;
	}
	N++;
}



public void insert(int i ,T t){
	Node pre = head;
	for(int index=0;index<i;index++){
		pre= pre.next;
	}
	Node curr =pre.next;
	Node newNode =new Node (t,pre,curr);
	pre.next=newNode;
	curr.pre=newNode;
	N++;
}


public T remove(T t){
	Node pre = head;
	for(int index=0;index<i;index++){
		pre= pre.next;
	}
	Node curr =pre.next;
	Node nextnode = curr.next;
	pre.next=nextnode;
	nextnode.pre= pre;
	N--;
	return curr.item;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值