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

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值