主要学习了链表的初始化、插入、删除
package second;
public class Linklist {
//需要一个Node类来充当结点的模型。一个存放数据,一个存放下一节点的引用
class Node{
int data;
Node next;
public Node(int value) {
data=value;
next=null;
}
}
Node header;
public Linklist() {
header=new Node(0);
}
public String toString() {
String resultString="";
if(header.next==null) {
return "empty";
}
Node node=header.next;
while(node!=null) {
resultString+=node.data+", ";
node=node.next;
}
return resultString;
}
public void reset() {
header.next=null;
}
//查找
public int locate(int value) {
int position=-1;
Node node=header.next;
int currentposition=0;
while(node!=null) {
if(node.data==value) {
position=currentposition;
break;
}
node=node.next;
currentposition++;
}
return position;
}
//插入
public boolean insert(int position,int value) {
Node node=header;
Node newnode;
for(int i=0;i<position;i++) {
if(node.next==null) {
System.out.println("The position " + position + " is illegal.");
return false;
}
node=node.next; //往后移一个结点,指向下一个结点
}
newnode=new Node(value);
newnode.next=node.next; //将新的节点指向原来节点的下一节点
node.next=newnode; // 原来的节点指向现在新的节点
return true;
}
public boolean delete(int position) {
Node node=header;
for(int i=0;i<position;i++) {
if(node.next==null) {
System.out.println("The position " + position + " is illegal.");
return false;
}
node=node.next;
}
node.next=node.next.next;//将结点指向下一个结点的下一个结点,即可删除中间结点
return true;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Linklist linklist=new Linklist();
//插入操作
for(int i=0;i<5;i++) {
linklist.insert(0, i);
}
System.out.println("After inserting,the list is: "+linklist.toString());
linklist.insert(6, 9);
System.out.println("After inserting,the list is: "+linklist.toString());
//删除操作
linklist.delete(3);
System.out.println("After deleting,the list is: "+linklist.toString());
linklist.delete(0);
System.out.println("After deleting,the list is: "+linklist.toString());
linklist.reset();
System.out.println("After reseting,the list is: "+linklist.toString());
}
}