Java实现创建简单的链表操作

1、创建Node节点类

//构建节点类
public class Node {
	int data;
	int np;
	String names;
	Node next;
	//节点声明的构造函数
	public Node(int data, int np, String names) {
		this.data = data;
		this.np = np;
		this.names = names;
		this.next=null;
	}
}

2、定义两个Node类型的节点指针,分别指向头节点和尾结点,并定义添加节点的方法

package List;
import java.util.*;
//定义两个Node类型的节点指针
public class LinkedList{
	private Node first;
	private Node last;
	public Node BooleanisEmpty() {
		return first =null;
	}
	//输入节点
	public void print() {
		Node  current=first;
		while(current!=null)
		{
			System.out.println("["+current.data+""+current.names+""+current.np+"]");
			current=current.next;
		}
		System.out.println();
	}
	//插入元素
	public void insert(int data,String names,int np) {
		Node newNode=new Node(data,np,names);
		if(first==null){
			first=newNode;
			last=newNode;
		}
		else {
		last.next=newNode;
		last=newNode;
		}
	}
}

3、实例,添加5个学生的信息

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class CH01_01 {

public static void main(String[] args) throws  IOException {
	BufferedReader buf=new BufferedReader(new InputStreamReader(System.in));
	int num;
	String name;
	int score;
	System.out.println("请输入5名学生数据:");
	LinkedList list=new LinkedList();
	for(int i=1;i<6;i++) {
		System.out.println("请输入学号:");
		num=Integer.parseInt(buf.readLine());
		System.out.println("请输入姓名:");
		name=buf.readLine();
		System.out.println("请输入成绩:");
		score=Integer.parseInt(buf.readLine());
		list.insert(num,name,score);
		System.out.println("--------------");
	}
	System.out.println("学生 成绩");
	System.out.println("学号 姓名 成绩 =======");
	list.print();	
}
}

输出:
请输入5名学生数据:
请输入学号:
01
请输入姓名:
黄晓华
请输入成绩:
85
--------------
请输入学号:
02
请输入姓名:
方小源
请输入成绩:
95
--------------
请输入学号:
03
请输入姓名:
林大辉
请输入成绩:
88
--------------
请输入学号:
04
请输入姓名:
孙阿毛
请输入成绩:
90
--------------
请输入学号:
05
请输入姓名:
王小明
请输入成绩:
77
--------------
学生 成绩
学号 姓名 成绩 =======
[1黄晓华85]
[2方小源95]
[3林大辉88]
[4孙阿毛90]
[5王小明77]

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值