算法通关村-第一关链表

一、单链表的定义

	单链表是一种链式存储的数据结构,用一组地址任意的存储单元来存放线性表中的数据元素。
	单链表就像一个铁链一样,元素之间相互连接,包含多个节点,每个节点有一个指向后继元素的next指针。
表中最后一个元素指向NULL。

单链表结构
单链表结构
JVM中单链表结构
在这里插入图片描述

二、单链表的创建

	面向对象:
public class ListNode{
	private int data;
	private ListNode next;
	public ListNode(int data){
		this.data = data;
	}
	public int getData(){
		return data;
	}
	public void setData(int data){
		this.data = data;
	}
	public ListNode getNext(){
		return next;
	}
	public void setNext(ListNode next){
		this.next = next;
	}
}

三、单链表的操作

3.1 单链表插入

public static Node insertNode(Node head, Node nodeInsert, int position){
	if(head == null){
		return nodeInsert;
	}
	int size = getLength(head);
	if(position > size+1 || position < 1){
		System.out.println("位置参数越界");
		return head;
	}
	//表头插入
	if(position == 1){
		nodeInsert.next = head;
		head = nodeInsert;
		return head;
	}
	Node pNode = head;
	int count = 1;
	//这里position被size限制住了,不用考虑pNode = null
	while(count < position -1){
		pNode = pNode.next;
		count++;
	}
	nodeInsert.next = pNode.next;
	pNode.next = nodeInsert;
	return head;
}

3.2 求链表长度/链表遍历

public static int getListLength(Node head){
	int length = 0;
	Node node = head;
	while(node != null){
		length++;
		node = node.next;
	}
	return length;
}

3.3 链表删除

public static Node deleteNode(Node head, int position){
	if(head == null){
		return null;
	}
	int size = getListLength(head);
	if(position > size || position < 1){
		System.out.println("输入的参数有误");
		return head;
	}
	if(position == 1){
		return head.next;
	}
	else
	{
		Node preNode = head;
		int count = 1;
		while(count < position - 1){
			preNode = preNode.next;
			count++;
		}
		Node curNode = preNode.next;
		preNode.next = curNode.next;
	}
	return head;
}

四、总结

	对于单链表,不管进行什么操作,都一定是从头开始逐个向后访问,所以单链表易增删,不易查询。
	单链表插入和删除,需要考虑表头、内部、表尾三种情况,单链表内部插入和删除的顺序尤为重要。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值