【数据结构】单链表(一)单链表的定义,插入,删除和查找操作

单链表是一种非常适合插入和删除的数据结构,但是查找和修改时间复杂度为O(N)

节点部分:

首先定义一个value来存放值,再定义一个指针来指向下一个节点

	int val;
	Node next;


然后定义构造函数并初始化节点的值

	Node(int val) {
		this.val = val;
		this.next = null;
	}



链表部分:

首先定义头指针和尾指针

	Node head;
	Node tail;


然后是基本操作:增删查

头插:

	public void insertBefore(Node newNode) {
		newNode.next = head;
		head = newNode;
	}

尾插:

	public void insertAfter(Node newNode) {
		if (head == null)
			head = tail = newNode;
		else {
			tail.next = newNode;
			tail = newNode;
		}
	}

为什么尾插需要判空而头插不需要?

因为如果tail为空,tail.next必定出现空指针错误。而头插法没有出现head.xxx这样的情况


头删:

	public void deleteBefore() {
		if (head == null) {
			System.out.println("linkedlist is empty");
			return;
		}		
		else
			head = head.next;
	}

尾删:

	public void deleteAfter() {
		if (head == null) {
			System.out.println("linkedlist is empty");
			return;
		}
		if (head.next == null)
			head = null;
		else {
			Node runner = head;
			while (runner.next.next != null)
				runner = runner.next;
			runner.next = runner.next.next;
		}
	}


我们可以看出,尾删的时间复杂度是最高的,因为要一个while循环来找最后一个元素,所以尽量避免用尾删,后面的栈和队列操作我们会更深入的理解。


根据“值”查找节点位置:

	public int searchIndex(int value) {
		int counter = 1;
		Node runner = head;

		while (runner != null) {
			if (runner.val == value)
				return counter;
			else {
				runner = runner.next;
				counter++;
			}
		}
		return -1;
	}

根据“节点位置”查找值:

	public String searchValue(int index) {
		int counter = 1;
		Node runner = head;

		while (runner != null) {
			if (index == counter)
				return runner.item;
			else {
				runner = runner.next;
				counter++;
			}
		}
		return "out of index!";
	}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值