java实现单链表的基本操作

package link;
/**
 * 单链表模型:实现插入、删除、查找、反转、输出等操作
 * @author USER
 *
 */

//结点类
class Node{
	protected int data; //结点数据
	protected Node next;	//结点指针
	
	//结点构造方法
	public Node(int data) {
		this.data=data;
	}
	
	public void print() {
		System.out.print(data+" ");
	}
	
}

//链表类
class Link{
	public  Node head;//头结点
	private int pos = 0;	//结点位置
	
	public Link(){
		this.head = null;
	}
	
	//插入一个头结点
	public void addHeadNode(int data) {
		Node node = new Node(data);
		node.next = head;//此处head为null
		head = node;//此处head为新加入的结点
	}
	
	//在任意位置index处插入一个结点,插入结点在index之后的那个结点
	public void add(int index, int data) {
		Node node = new Node(data);
		Node previous = head;
		Node current = head;
		while (pos!=index) {
			previous = current;
			current = current.next;
			pos++;
		}
		node.next = current;
		previous.next = node;
		pos = 0;
	}
	
	//在任意位置index处删除一个结点,删除的是第index个结点,不能删除第一个结点
	public void delete(int index) {
		Node previous = head;
		Node current = head;
		pos++;
		while (pos!=index) {
			previous = current;
			current = current.next;
			pos++;
		}
		previous.next = current.next;
		pos = 0;
	}
	
	//删除头结点
	public void deleteHead() {
		Node temp = head;
		head = temp.next;
	}
	
	//根据结点位置查找结点信息,注意:index是指第几个位置,pos是从0开始代表第一个位置
	public Node findByPos(int index) {
		Node current = head;
		pos++;
		while (pos != index) {
			current = current.next;
			pos++;
		}
		pos = 0;
		return current;
	}
	
	//根据结点数据查找结点信息
	public Node findByData(int data) {
		Node current = head;
		while (current.data != data) {
			if (current.next == null) {
				return null;
			}else {
				current = current.next;
			}
		}
		return current;
	}
	
	//整个链表的长度
	public  int length() {
		int size = 0;
		Node current = head;
		while (current != null) {
			current = current.next;
			size++;
		}
		return size;
	}
	
	//显示整个链表
	public void show() {
		Node current = head;
		while (current != null) {
			current.print();
			current = current.next;
		}
		System.out.println();
	}
	
}

public class MySingleLinkList {
	public static void main(String[] args) {
		Link list = new Link();
		list.addHeadNode(10);
		list.show();//10
		
		list.add(1, 12);
		list.add(2, 13);
		list.add(3, 14);
		list.add(4, 15);
		list.add(5, 16);
		list.show();//10 12 13 14 15 16
		System.out.println(list.length());//6
		
		list.delete(2);
		list.show();//10 13 14 15 16
		list.delete(2);
		list.show();//10 14 15 16
		System.out.println(list.length());//4
		
		list.deleteHead();
		list.show();//14 15 16
		
		System.out.println(list.findByPos(2).data);//15
		System.out.println(list.findByPos(3).data);//16
		System.out.println(list.findByData(15).data);//15
	}
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值