/**
*
*/
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