栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java实现链表基础-单向链表插入新节点

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java实现链表基础-单向链表插入新节点

设计一个Java程序,来实现单向链表添加节点的过程,并且允许可以在链表头部、链表末尾和链表中间三种不同位置插入新节点。

package linkList;

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

package linkList;

public class insert {
	public Node1 first;
	public Node1 last;
	public boolean isEmpty(){
		return first==null;
	}
	public void print() {
		Node1 current=first;
		while(current!=null) {
			System.out.print("["+current.data+"]");
			current=current.next;
		}
		System.out.println();
	}
	public insert Concatenate(insert head1,insert head2) {
		insert ptr;
		ptr=head1;
		while(ptr.last.next!=null) ptr.last=ptr.last.next;
		ptr.last.next=head2.first;
		return head1;
	}
	public void insert(Node1 ptr) {
		Node1 temp;
		Node1 newNode;
		if(this.isEmpty()) {
			first=ptr;
			last=ptr;
		}else {
			if(ptr.next==first) {
				ptr.next=first;
				first=ptr;
				
			}else {
			if(ptr.next==null) {
				last.next=ptr;
				last=ptr;
			}else {
				temp=first;
				newNode=first;
				while(ptr.next!=newNode.next) {
					temp=newNode;
					newNode=newNode.next;
				}
				temp.next=ptr;
				ptr.next=newNode;
			}
			}
			
		}
	}
	
	
}

package linkList;

public class InsertTest {
	public static void main(String args[]) {
		insert list1=new insert();
		insert list2=new insert();
		Node1 node1=new Node1(5);
		Node1 node2=new Node1(6);
		list1.insert(node1);
		list2.insert(node2);
		Node1 node3=new Node1(7);
		Node1 node4=new Node1(8);
		list2.insert(node3);
		list2.insert(node4);
		list1.Concatenate(list1, list2);
		list1.print();
		
	}
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/490297.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号