package singlelinkist;
public class Node {
int num;
String name;
Node next;
public Node ( )
{
}
public Node ( int num, String name)
{
this . num= num;
this . name= name;
}
@Override
public String toString ( ) {
return "Node{" +
"num=" + num +
", name='" + name + '\'' +
'}' ;
}
}
package singlelinkist;
import java. util. Scanner;
public class LinkList {
Node head = new Node ( ) ;
public void addByTail ( Node node) {
Node temp= head;
while ( temp. next!= null)
temp= temp. next;
temp. next= node;
}
public int find ( int num) {
Node temp = head. next;
int loc = 0 ;
while ( temp != null && temp. num != num) {
temp = temp. next;
loc++ ;
}
if ( temp != null)
return loc;
else
return - 1 ;
}
public int update ( int num) {
Node temp = head. next;
while ( temp != null && temp. num != num) {
temp = temp. next;
}
if ( temp != null) {
System. out. println ( "请输入新的学号和姓名:" ) ;
Scanner scanner = new Scanner ( ( System. in) ) ;
int newNum = scanner. nextInt ( ) ;
String newName = scanner. next ( ) ;
temp. num= newNum;
temp. name= newName;
return 1 ;
}
else
{
return - 1 ;
}
}
public int insert ( int loc, Node newNode)
{
int count= 0 ;
if ( loc< 1 || loc> size ( ) + 1 )
{
System. out. println ( "插入位置有误" ) ;
return - 1 ;
}
else {
Node pre= head;
while ( count!= loc- 1 )
{
count++ ;
pre= pre. next;
}
Node temp= pre. next;
pre. next= newNode;
newNode. next= temp;
return 1 ;
}
}
public int delete ( int num)
{
Node pre= head;
while ( pre. next!= null&& pre. next. num!= num)
pre= pre. next;
if ( pre. next== null)
return - 1 ;
else {
pre. next= pre. next. next;
return 1 ;
}
}
public int size ( )
{
int count= 0 ;
Node temp= head. next;
while ( temp!= null)
{
count++ ;
temp= temp. next;
}
return count;
}
public void show ( )
{
Node temp = head. next;
while ( temp != null) {
System. out. println ( temp) ;
temp = temp. next;
}
}
}
package singlelinkist;
public class LinkListTest {
public static void main ( String args[ ] )
{
LinkList linkList= new LinkList ( ) ;
Node node1= new Node ( 1001 , "Tom" ) ;
Node node2= new Node ( 1002 , "Mike" ) ;
Node node3= new Node ( 1003 , "Bob" ) ;
Node node4= new Node ( 1004 , "Jack" ) ;
linkList. addByTail ( node1) ;
linkList. addByTail ( node2) ;
linkList. addByTail ( node3) ;
linkList. addByTail ( node4) ;
linkList. show ( ) ;
int x1= linkList. find ( 1008 ) ;
System. out. println ( "1008的位置:" + x1) ;
int x2= linkList. find ( 1003 ) ;
System. out. println ( "1003的位置:" + x2) ;
System. out. println ( linkList. size ( ) ) ;
Node node5= new Node ( 1000 , "Sara" ) ;
linkList. insert ( 1 , node5) ;
linkList. show ( ) ;
System. out. println ( ) ;
Node node6= new Node ( 1005 , "Jim" ) ;
linkList. insert ( 6 , node6) ;
linkList. show ( ) ;
System. out. println ( ) ;
linkList. delete ( 1000 ) ;
linkList. show ( ) ;
System. out. println ( ) ;
linkList. delete ( 1005 ) ;
linkList. show ( ) ;
}
}