package cn.day18;
import java.util.ArrayList;
import com.sun.org.apache.regexp.internal.recompile;
public class LinkData {
public ListNode addLinkNade(ListNode headNode ,ListNode insertNode){
if(headNode == null){
headNode = insertNode;
return headNode;
}else{
ListNode pNode = headNode;
while(pNode.getNextNode() != null){
pNode = pNode.getNextNode();
}
ListNode currentNode = pNode.getNextNode();
insertNode.setNextNode(currentNode);
pNode.setNextNode(insertNode);;
return headNode;
}
}
/**
* 指定位置删除链表
* @param headNode
* @return
*/
public ListNode deleteListNodeByPosition(ListNode headNode,int position){
if(headNode == null){
return headNode;
}
if(position == 1){//删除表头
ListNode currentNode = headNode.getNextNode();
headNode = null;
return currentNode;
}else{//删除中间或未尾
ListNode pNode = headNode;
int count = 1;
while (count < position -1){
count++;
pNode = headNode.getNextNode();
}
ListNode currentNode = pNode.getNextNode();
pNode.setNextNode(currentNode.getNextNode());
currentNode = null;
}
return headNode;
}
/**
* 打印链表
* @param headNode
*/
public void printListNode(ListNode headNode){
if(headNode == null){
System.out.println("链表为空!!!");
return ;
}
while(headNode.getNextNode() != null){
System.out.println();
}
}
/**
* 获取链表大小
* @param headNode
* @return
*/
public int getSize(ListNode headNode){
int count = 0;
if (headNode != null){
count =1;
}
ListNode pNode = headNode;
while(pNode.getNextNode() != null){
pNode = pNode.getNextNode();
count++;
}
return count;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ListNode headNode = null;
LinkData link = new LinkData();
ListNode node1 = new ListNode(10);
headNode = link.addLinkNade(headNode,node1);
ListNode node2 = new ListNode(20);
headNode = link.addLinkNade(headNode,node2);
ListNode node3 = new ListNode(30);
headNode = link.addLinkNade(headNode,node3);
link.deleteListNodeByPosition(headNode, 2);
System.out.println(headNode);
System.out.println("大小==="+link.getSize(headNode));
}
}