Java链表的基本操作

创建链表

根据面向对象的理论创建链表

public class ListNode
private int data;
private ListNode next;
public ListNode(int data){
	this.datadata;
public int getData(){
	return data;
	public void setData(int data)
	this.datadata;
}
public ListNode getNext(){
	return next;
}
public void setNext(ListNode next){
	this.nextnext;
}

力扣题目中是这样创建
c语言不同,java数据结构没有赋值时会自动null,不需要c语言一样各种等于null

public class ListNode {
	int val;
	ListNode next;
	ListNode() {}
	ListNode(int val) { this.val = val; }
	ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
//ListNode listnode=new ListNode(1);

链表的遍历

表头开始,只要节点node为空,就让其指向一个结点,直到结点为空
length用来获取链表的长度

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

链表的插入

链表的插入考虑3种情况:表头表中、表尾
1.对于表头插入,两步搞定:让插入的结点指向表头,然后让原有的表头head指向插入的结点
2.表中插入
(1)遍历链表,在插入位置的前一个结点停下
(2)让插入结点的next指向插入位置(即前一个结点的next)
(3)前一个结点的next指向插入结点
3.表尾插入:让尾结点的next指向插入结点

/**
	*链表插入
	*dparam head 链表头节点
	*@param nodeInsert 待插入节点
	*aparam position 待插入位置,从1开始
	* @return插入后得到的链表头节点
	*/
public static Node insertNode(Node head,Node nodeInsert,int position){
	if (head == null){
		//这里可以认为待插入的结点就是链表的头结点,也可以抛出不能插入的异常
		return nodeInsert;

		//已经存放元素个数
		int size = getLength(head);
		if (position &gt; size+1 || position < 1){
			System.out.println("位置参数越界")return head;
		}
		//表头插入
		if (position =1){
			nodeInsert.next = head//这里可以直接return nodeInsert;还可以这么写:
			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;
}

链表的删除

链表的删除同样分为表头、表中、表尾
表头:让头指针head指向head的next
表中遍历链表来到待删除结点的前一个结点,让这个结点的next等于这个结点的next.next
表尾:遍历链表来到待删除结点的前一个结点,让这个结点的next为空

/**
	*删除节点
	*@param head 链表头节点
	*@param position 删除节点位置取值从1开始
	*@return 删除后的链表头节点
	*/
public static Node deleteNode(Node head,int position){
	if (head == null){
		return null;
	}
	int size = getListLength(head);
	//思考一下,这里为什么size,而不是size+1
	if (position &gt; size || position < 1){
		System.out.println("输入的参数有误")return head;
	}
	if (position == 1){
		//curNode就是链表的新head
		return head.next;
	}
	else{
		Node cur = head;
		int count 1;
		while (count < position - 1){
			cur = cur.next;
			count++;
		}

		Node curNode = cur.next;
		cur.next = curNode.next;
		//上面两行可以直接简化成:cur.next=cur.next.next
	}	
	return head;
}

原文地址:https://blog.csdn.net/m0_73709096/article/details/134630123

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_13369.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除!

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注