java实现链表以及相关操作

本篇博文主要介绍使用java实现链表的基本操作,在链表末尾添加新元素、删除任意位置的元素、进行插入排序、打印链表内容,代码实现如下。

class Node
{
	Node next =null;
	int data;
	public Node(int data)
	{
		this.data = data;
	}
}

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;
	}

	/*
	* 返回指定链表的长度
	*/
	public int length()
	{
		int length = 0;
		Node tmp = head;
		while(tmp != null)
		{
			length++;
			tmp = tmp.next;
		}
		return length;
	}

	/*
	* 删除指定位置的元素
	*/
	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 (index == i)
			{
				preNode.next = curNode;
				return true;
			}
			preNode = curNode;
			curNode = curNode.next;
			i++;
		}
		return true;
	}

	/*
	* 对当前链表进行排序并返回排序后的头结点
	*/
	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(8);
		list.addNode(2);
		System.out.println(list.length());

		list.printList();
		list.orderList();
		list.printList();
	}
}


已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 酷酷鲨 设计师:CSDN官方博客 返回首页