Home - GeorgeZhung/-1 GitHub Wiki
package ds_ch5llrhw_110207; class Node { //串列節點類別 int data; //節點資料 Node next; //指向下一個節點的指標 public Node(int data) { //建構子:建立節點 this.data=data; next=null; } }
abstract class List { public Node first_node, current_node; abstract boolean isListEmpty();//抽象方法:檢查串列是否是空的 abstract void printList(); //抽象方法:顯示串列資料 }
class SinglyLinked extends List { Node head,temp; public SinglyLinked(int[] array){ //建構子:建立單向鏈結串列 Node singlylinked[]=new Node[array.length];
for(int i = array.length-1; i >= 0; i--){
if(i == array.length-1) {
singlylinked[i] = new Node(array[i]);
}
else{
singlylinked[i] = new Node(array[i]);
singlylinked[i].next = singlylinked[i+1];
}
}
head=singlylinked[0];
}
//方法:檢查串列是否是空的
public boolean isListEmpty(){
return head==null;
}
//方法:顯示串列資料
public void printList(){
temp=head;
if(isListEmpty() != true) {
while(temp.next != null) {
System.out.print(temp.data+" ");
temp = temp.next;
}
System.out.print(temp.data);
}
}
//方法:搜尋節點資料
public Node searchNode(int d){
temp = head;
if(isListEmpty() != true) {
while(temp.next != null) {
if(temp.data == d) {
System.out.print("鏈結串列中有此資料");
return temp;
}else{
temp = temp.next;
}
}
if(temp.data == d) {
System.out.print("鏈結串列中有此資料");
return temp;
}
}
System.out.print("鏈結串列中無此資料");
return null;
}
//方法:反轉鏈結串列
public void ReverseList(){
Node current = null,previous;
while(head.next != null) {
previous = current;
current = head;
head = head.next;
current.next = previous;
}
previous = current;
current = head;
current.next = previous;
}
//查詢鏈結串列的長度
public int ListLength(){
temp = head;
int count = 0;
if(isListEmpty() != true) {
count++;
while(temp.next != null) {
count++;
temp = temp.next;
}
}
return count;
}
}
public class DS_CH5LLRHW_110207 {
public static void main(String[] args) {
int [] data = {1,4,10,15};//建立串列的陣列
SinglyLinked sl = new SinglyLinked(data);//建立串列
System.out.print("原來的串列:");
sl.printList();//顯示串列
sl.ReverseList();//反轉鏈結串列
System.out.print("反轉後的串列:");
sl.printList();//顯示串列
System.out.println("串列長度:"+ sl.ListLength());
}
}