唉,說點(diǎn)廢話,昨天偶爾看到一年前自己用C解約瑟夫環(huán)問題的循環(huán)鏈表,唏噓不已,想想自己一年前嵌入式的夢呢,這兩天發(fā)生了許多,而有些人不在了就真的不在了,心情不好,不多說了,直接上代碼,只是些鏈表的基本操作,花些功夫看就好了。
首先,建立一個(gè)Node類,里面內(nèi)構(gòu)一個(gè)Node對象和數(shù)據(jù)(用來區(qū)分);
public class Node { PRotected Node next; //指針 protected int data; //數(shù)據(jù) public Node(int data){ this.data = data; } //顯示節(jié)點(diǎn) public void display(){ System.out.println(data+" "); }}然后創(chuàng)建一個(gè)LinkList類,里面包含了鏈表的一些基本方法,
public class LinkList { public Node first; //定義一個(gè)頭結(jié)點(diǎn) public LinkList(){ this.first = null; } //插入一個(gè)頭結(jié)點(diǎn) public void addFirstNode(int data){ Node node = new Node(data); node.next = first; first = node; } //刪除一個(gè)頭節(jié)點(diǎn),并返回頭結(jié)點(diǎn) public Node deleteFirstNode(){ Node tempNode = first; first = tempNode.next; return first; } //在替換掉index后面的節(jié)點(diǎn)。 public void add(int index , int data){ Node node = first; Node current = first; while(index-->0){ current = node.next; node = current; } current.data = data; } //在第index節(jié)點(diǎn)后面插入節(jié)點(diǎn) public void Insert(int index , int data){ Node node = new Node(data); Node current = first; Node privious = first; while(index-->0){ privious = current; current = current.next; } node.next = current; privious.next = node; } //刪除任意位置的節(jié)點(diǎn) public void delete(int index){ Node current = first; Node privious = first; while(index-->0){ privious = current; current = current.next; } if(current == first){ first = first.next; }else{ privious.next = current.next; } } //根據(jù)data的值刪除節(jié)點(diǎn),刪除找到的第一個(gè)節(jié)點(diǎn) public void deleteData (int data){ Node privious = first; Node current = first; while(current.data!=data){ privious = current; current = current.next; } if(current == first){ first = first.next; }else{ privious.next = current.next; } }}再建立一個(gè)主類,
public class TestLink { public static void main(String[] args){ LinkList l = new LinkList(); l.addFirstNode(1); l.addFirstNode(2); l.addFirstNode(3); Node node = l.first; l.Insert(2, 5); l.deleteData(5); while(node!=null){ node.display(); node = node.next; } }}實(shí)在是沒有心情繼續(xù)寫了,希望以后會(huì)好點(diǎn),2015年8月9日18:55分。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注