链表的java实现以及基本的增加,删除,排序操作

本文详细介绍了链表的数据结构及其基本操作,包括插入、删除、获取长度和排序等,并通过实例展示了如何使用这些操作。

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

首先是存储节点信息的数据类

package com.list;

public class Node {
	Node next=null;
	int data;
	public Node(int data){
		this.data=data;
	}
}
链表的基本操作

package com.list;

public class MyLinkedList {
	Node head=null;
	//插入数据
	public void addNode(int d){
		Node newNode=new Node(d);
		if(head==null){
			head=newNode;
			return;
		}
		Node tmp=head;
		while(tmp.next!=null){
			tmp=tmp.next;
		}
		tmp.next=newNode;
	}
	//删除第index个结点
	public boolean deleteNode(int index){
		if(index<1||index>length()){
			return false;
		}
		//删除第一个元素
		if(index==1){
			head=head.next;
			return true;
		}
		int i=1;
		Node preNode=head;
		Node curNode=preNode.next;
		while(curNode!=null){
			if(i==index){
				preNode.next=curNode.next;
				return true;
			}
			preNode=curNode;
			curNode=curNode.next;
			i++;
		}
		return true;
	}
	//返回结点的长度
	public int length(){
		int length=0;
		Node tmp=head;
		while(tmp!=null){
			length++;
			tmp=tmp.next;
		}
		return length;
	}
	//对链表进行排序
	public Node orderList(){
		Node nextNode=null;
		int temp=0;
		Node curNode=head;
		while(curNode.next!=null){
			nextNode=curNode.next;
			while(nextNode!=null){
				if(curNode.data>nextNode.data){
					temp=curNode.data;
					curNode.data=nextNode.data;
					nextNode.data=temp;
				}
				nextNode=nextNode.next;
			}
			curNode=curNode.next;
		}
		return head;
	}
	public void printList(){
		Node tmp=head;
		while(tmp!=null){
			System.out.println(tmp.data);
			tmp=tmp.next;
		}
	}
	public static void main(String[] args) {
		MyLinkedList list=new MyLinkedList();
		list.addNode(5);
		list.addNode(3);
		list.addNode(1);
		list.addNode(3);
		System.out.println("listLen="+list.length());
		System.out.println("before order:");
		list.printList();
		list.orderList();
		System.out.println("after order:");
		list.printList();
	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值