代码实现
第一部分:创建一个节点类
public class Node {
public int num;
public String name;
public int age;
public Node next;
public Node ( int num, String name, int age) {
this . num = num;
this . name = name;
this . age = age;
}
public String toString ( ) {
return "编号:" + num+ "-----姓名:" + name+ "-----年龄:" + age;
}
}
第二部分:创建一个链表类(实现增删改查功能)
package com. jianning. linkdlist;
public class LinkdList {
private static Node head = new Node ( 0 , "" , 0 ) ;
public void addNode ( Node newnode) {
Node temp = head;
while ( true ) {
if ( temp. next == null) {
break ;
}
temp = temp. next;
}
temp. next = newnode;
}
public void add ( Node newnode) {
Node temp = head;
while ( true ) {
if ( temp == null) {
System. out. println ( "没有找到位置添加" ) ;
break ;
}
if ( temp. num < newnode. num || temp. next. num > newnode. num) {
newnode. next = temp. next;
temp. next = newnode;
break ;
}
temp = temp. next;
}
}
public void del ( int n) {
Node temp = head;
if ( head. next == null) {
System. out. println ( "该链表为空~~" ) ;
}
else {
while ( true ) {
if ( temp. next == null) {
System. out. println ( "没有找到该编号所对应的节点" ) ;
break ;
}
if ( temp. next. num == n) {
temp. next = temp. next. next;
break ;
}
temp = temp. next;
}
}
}
public void alt ( int n, String name, int a) {
Node temp = head;
if ( head. next == null) {
System. out. println ( "链表为空~~" ) ;
}
else {
while ( true ) {
if ( temp. next == null) {
System. out. println ( "没有找到该序号所对应的节点" ) ;
break ;
}
if ( temp. next. num == n) {
temp. next. name = name;
temp. next. age = a;
break ;
}
temp = temp. next;
}
}
}
public static void show ( ) {
Node temp = head;
if ( head. next == null) {
System. out. println ( "链表为空~~" ) ;
}
else {
while ( true ) {
if ( temp. next == null) {
break ;
}
temp = temp. next;
System. out. println ( temp) ;
}
}
}
}
第三部分:测试
public class LinkdListDome {
public static void main ( String[ ] args) {
Node a = new Node ( 2 , "安琪拉" , 7 ) ;
Node b = new Node ( 3 , "铠" , 25 ) ;
Node c = new Node ( 4 , "老夫子" , 60 ) ;
Node d = new Node ( 1 , "鲁班" , 5 ) ;
LinkdList list = new LinkdList ( ) ;
list. show ( ) ;
list. addNode ( a) ;
list. addNode ( b) ;
list. addNode ( c) ;
list. add ( d) ;
list. show ( ) ;
System. out. println ( "***********删除后的链表*************" ) ;
list. del ( 7 ) ;
list. show ( ) ;
System. out. println ( "***********修改后的链表**************" ) ;
list. alt ( 4 , "孙尚香" , 20 ) ;
list. show ( ) ;
}
}
第四部分:结果