(一) 链表 - 插入删除基本操作

链表:一种用于存储数据集合的数据结构

链表的属性:1. 相邻元素之间通过指针连接

                     2.最后一个元素的后继元素为null

                     3.链表的空间可以按需分配(直到系统内存耗尽)

                    4.没有内存空间的浪费(但是链表当中的指针需要一些额外的内存花销)

链表和数组的区别:

(1)数组存储在一块连续的内存空间中,而链表的存储位置不是连续的

(2)当数组规模很大时,有时没办法分配能存储整个数组的空间,链表则不需要考虑

(3)数组的大小是静态的,链表可以在常数时间内进行扩展

(4)数组存在数组下标元素之间又是物理相邻的,所以数组的内存地址可以通过:数据类型存储空间的大小*数组下标+基地址 进行计算,因为运算执行的时间为常数时间所以认为数组的访问操作能在常数时间完成,链表中查找特定位置的元素则比较困难,需要遍历。

(5)数组基于位置的插入删除操作比较复杂,较多情况下需要大量移动数组元素的位置,而链表则可以比较简单的进行插入删除操作

单向链表:

(一)单向链表类型声明

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

}

(二)计算链表元素个数,时间复杂度O(n),空间复杂度O(1)仅用于创建临时变量

	public int ListLength(ListNode headNode){
		int length = 0;
		ListNode currentNode = headNode;
		while(currentNode!=null){
			length++;
			currentNode = currentNode.getNext();
		}
		return length;
	}

(三)单向链表的插入

public ListNode InsertInListList(ListNode headNode, ListNode NodeToInsert, int position){
		if(headNode == null)
			return NodeToInsert;
		int size = ListLength(headNode);
		if(position>size+1||position<1){
			System.out.println("位置错误");
                        return null;
                 }
		//在链表头部插入
		if(position == 1){
			NodeToInsert.setNext(headNode);
			return NodeToInsert;
		}else{
			//在链表中间或尾部插入
			int count = 1;
			ListNode currentNode = headNode;
			while(count<position-1){
				headNode = headNode.getNext();
				count++;
			}
			ListNode tempNode = headNode.getNext();
			NodeToInsert.setNext(tempNode);
			headNode.setNext(NodeToInsert);
			return currentNode;
		}
		
	}

(四)单向链表的删除

	public ListNode DeleteNodeFromLinkedList(ListNode headNode, int position){
		int size = ListLength(headNode);
		if(position>size||position<1){
			System.out.println("位置错误");
			return null;
		}
		//删除链表头部节点
		if(position == 1){
			return headNode.getNext();
		}else{
			//删除链表中间和尾部节点
			ListNode currentNode = headNode;
			int count = 1;
			while(count<position-1){
				headNode = headNode.getNext();
				count++;
			}
			ListNode tempNode = headNode.getNext();
			headNode.setNext(tempNode.getNext());
			return currentNode;
		}
	}
(五)单链表的修改和删除基于链表的遍历





猜你喜欢

转载自blog.csdn.net/zz0129/article/details/80397457
今日推荐