/**
*
*/
package com.test.junit;
/**
* <pre>
* 鏈表結構
* </pre>
* @author ps
*
*/
public class Link {
Node head;
int length;
/**
* <pre>
* 結點
* </pre>
* @author ps
*/
class Node{
int data;
Node next;
}
/**
* <pre>
* 創建一個長度爲N的鏈表,而且各個結點的數據初始化爲其序號
* 當N爲0時,默認只創建頭指針
* </pre>
* @param n 長度
* @return 頭指針
*/
public void create(int n){
Node p1,p2;
p1 = new Node();
length = n==0?1:n;
while(n > 0){
p2 = new Node();
p2.next = p1;
p2.data = n;
p1 = p2;
n--;
}
head = p1;
}
/**
* 打印鏈表中的數據
* @param head 頭指針
*/
public void print(Node head){
int row = 0;
while(head.next != null){
System.err.print(head.data);
if(row < length -1){
System.err.print("||");
}
row ++;
head = head.next;
}
System.err.println();
}
/**
* <pre>
* 當插入位置大於鏈表長度時,插入該結點到末尾
* 當插入位置小於1時,插入結點到最前面
* 否則插入到相應的位置
* </pre>
* @param pos 位置
* @param data 數據
* @return 頭指針爲空是false,插入失敗時false,否則true
*/
public boolean insert(int pos,int data){
if(head == null){
return false;
}
if(pos > length){//當插入位置大於鏈表長度時,插入該結點到末尾
pos = length + 1;
}else if(pos <= 1){//當插入位置小於1時,插入結點到最前面
pos = 1;
}
if(pos == 1){//插入結點到最前面
Node temp = new Node();
temp.next = head;
temp.data = data;
head = temp;
length ++;
return true;
}
int index = 1;
Node tempHead = head;
while(head.next != null){
if(index == pos-1){
Node temp = new Node();
temp.next = head.next;
temp.data = data;
head.next = temp;
head = tempHead;
length ++;
return true;
}
head = head.next;
index ++;
}
return false;
}
/**
* <pre>
* 刪除位置大於長度或者小於1時,刪除失敗
* </pre>
* @param pos 位置
* @return 頭指針爲空是false,刪除失敗時false,否則true
*/
public boolean delete(int pos){
if(head == null){
return false;
}
if(pos > length || pos < 1){//刪除位置大於長度或者小於1時,刪除失敗
return false;
}
if(pos == 1){//當刪除位置爲1時,直接刪除
head = head.next;
length --;
return true;
}
int index = 1;
Node tempHead = head;
Node temp = null;
while(head.next != null){
if(index == pos){
temp.next = head.next;
head = tempHead;
length --;
return true;
}
temp = head;
head = head.next;
index ++;
}
return false;
}
/**
* 返回鏈表的大小
* @return
*/
public int size(){
return length;
}
/**
* 判斷鏈表是否爲空
* @return
*/
public boolean isEmpty(){
return length == 0 ? true : false;
}
public static void main(String[] args) {
Link link = new Link();
link.create(10);
link.print(link.head);
link.insert(12, 11);
link.print(link.head);
link.delete(11);
link.print(link.head);
/*Scanner scanner = new Scanner(new BufferedInputStream(System.in));
while(scanner.hasNextInt()){
System.err.println(scanner.nextInt());
}*/
}
}
結果:
1||2||3||4||5||6||7||8||9||10
1||2||3||4||5||6||7||8||9||10||11
1||2||3||4||5||6||7||8||9||10