由於java中沒有結構體,所以用一個類來定義鏈表,代碼如下
主要包括一個data,還有一個指向后面一個節點的next
重寫了toString函數,返回你想要的數據
定義鏈表的類:
package LinkNode;
public class LinkNode {
public String data;
public LinkNode next;
public String getData(){
return data;
}
public void setData(String data){
this.data=data;
}
public LinkNode getNext(){
return next;
}
public void setNext(LinkNode next){
this.next=next;
}
public LinkNode(String data,LinkNode next){
super();
this.data=data;
this.next=next;
}
public LinkNode(){
super();
}
@Override
public String toString(){
return "data:"+data+" next->"+next;
}
}
1.初始化鏈表:
public static void initLinkNode(LinkNode L){
L.setData("#");
L.setNext(null);
}
2.遍歷鏈表,返回鏈表的長度
public static int traverse(LinkNode L){
LinkNode p = L;
int count = 1;
while(p.next!=null){
p = p.next;
count++;
}
return count;
}
3.把鏈表L的data轉化為StringBuffer輸出,輸出結果為字符串
public static StringBuffer outputLinkNode(LinkNode L){
StringBuffer str = new StringBuffer("");
LinkNode p = L;
for(@SuppressWarnings("unused")
int i=0;;){
str.append(p.data);
if(p.next!=null){
p = p.next;
}
else{
break;
}
}
return str;
}
4.在鏈表L的尾部插入一個節點,值為data
public static void insertLinkNode(LinkNode L,String data){
LinkNode p = L;
LinkNode q = new LinkNode();
for(@SuppressWarnings("unused")
int i=0;;){
if(p.next==null){
q.setData(data);
q.setNext(null);
p.setNext(q);
System.out.println("Insert "+data+" success.");
break;
}
else{
p = p.next;
}
}
}
5.刪除第n個節點(從0開始)
public static void deleteLinkNode(LinkNode L,int n){
int count = 1;
LinkNode p = L;
for(@SuppressWarnings("unused")
int i;;){
if(count == n){
p.setNext(p.next.next);
break;
}
else{
count++;
p = p.next;
}
}
}
6.從index=n開始遍歷,如果后面出現str,則返回true否則返回false
public static int lastIndex(LinkNode L,String str){
LinkNode p = L;
int flag = 0;
for(int i=0;i<traverse(L);i++){
if(p.data==str){
//System.out.println(i);
flag = i;
}
p = p.next;
}
return flag;
}
測試程序:
package LinkNode;
public class Quarrel extends Method{
public static void main(String[] args){
LinkNode L = new LinkNode();
System.out.println("初始化:");
initLinkNode(L);
System.out.println(L.toString());
System.out.println("插入節點:");
insertLinkNode(L,"R");
insertLinkNode(L,"R");
insertLinkNode(L,"L");
insertLinkNode(L,"L");
insertLinkNode(L,"R");
insertLinkNode(L,"L");
System.out.println(L.toString());
int count = traverse(L);
System.out.println("節點個數:"+count);
StringBuffer str = outputLinkNode(L);
System.out.println(str);
//最后一個L的位置
int lastindex = lastIndex(L,"L");
System.out.println("最后一個L的位置:"+lastindex);
System.out.println("刪除一個節點");
deleteLinkNode(L,2);
count = traverse(L);
System.out.println("節點個數:"+count);
str = outputLinkNode(L);
System.out.println(str);
System.out.println(L.toString());
}
}
結果如下:

