【数据结构】单链表

本文介绍了单链表这种线性数据结构,强调了它只能单方向遍历的特性,并详细阐述了单链表的基本操作,如创建、插入和删除结点。还提供了使用Java实现单链表的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

单链表是一种线性数据结构,每个元素都存放在链表的一个结点中,结点之间由指针串联在一起,这样就形成了一条如同链的结构,固称作链表。**所谓单链表顾名思义就是只能单方向遍历的链表。**如下图所示:

在这里插入图片描述
单链表的基本操作

单链表最基本的操作包括创建一个单链表、向单链表中插入结点、从单链表中删除结点等。

java版本的实现

package dataStructure;

class Node{
	int data;
	Node next = null;
	
	//创建节点
	public Node(int d) {
		data = d;
		next = null;
	}
}

public class SingleList {
	
	//单链表的头结点
	Node head;
	
	public SingleList() {
		head = null;
	}
	
	//计算单链表长度
	int ListLength() {
		int length = 0;
		Node currentNode = head;
		
		// 遍历单链表
		while(currentNode != null) {
			length++;
			currentNode = currentNode.next;
		}
		return length;
	}
	//打印单链表
	 void Print() {
		Node cur = head;
		if(cur == null ) {
			System.out.print("null");
		}
		while(cur != null) {
			System.out.print(cur.data+"->");
			cur = cur.next;		
		}
		System.out.println();
	}
	
	//单链表的插入
	Node Insert(Node node,int position) {
		
		if(head == null ) {	
			head = node;
			return head; 
		}
		
		int size = ListLength();
		if(position < 1 || position > size+1) {
			System.out.println("违法插入");
			return head;
		}
		
		if(position == 1) {
			node.next = head;
			head = node;
			return head;
		}else {
			int count = 1;
			Node it = head;
			//找到插入的位置的前一个结点
			while(count < position-1) {
				it = it.next;
				count++;		
			}
			node.next = it.next;
			it.next = node;
		}
		return head;
		
	}
	//删除单链表指定的结点
	Node deleteNode(int position) {
		Node it = head;
		int size = ListLength();
		
		if(position > size || position < 1) {
			System.out.println("违法删除");
			return head;
		}
		
		if(position == 1) {
			Node currentNode = head.next;
			head = currentNode;
			return currentNode;
		}else { 
			int count = 1;
			while(count < position-1) {
				it = it.next;
				count++;
			}
			it.next =it.next.next;
						
		}
		
		return head;
	}
	
	//删除整个单链表
	Node deleteSingList() {
		Node cur = head;
		Node rear = head;
		head = null;
		while(cur != null) {
			rear = cur.next;
			cur= null;
			cur = rear;
		}
		
		return head;
	}
	
	public static void main(String[] args) {
		SingleList list = new SingleList();
		
		list.Insert(new Node(1),2);
	    list.Insert(new Node(3),2);
	    list.Insert(new Node(2),2);
		list.Print();
	    list.deleteNode(1);
		list.Print();
		list.deleteSingList();
		list.Print();
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值