此文是续上篇博客内容,包括很多经典的算法,也包括很多编程技巧,希望对广大朋友有帮助。
(8)//查找倒数第几个元素 public Node findBackthData(int num)
(9)//反转链表 public void reverseLink()
(10)public void printReverseLink(Node pNode)
(10)//找到列表中间的节点 public void findMidNode()
(11)//判断列表中是否有环路 public boolean isLoop()
(12)//在不知道头指针的情况下,删除该节点 public boolean deleteNode(Node node)
//查找倒数第几个元素
public Node findBackthData(int num){
if(num < 1 || num > length()){
return null;
}
Node preNode = head;
Node nextNode = head;
int i = 1;
while(i <= num){
nextNode = nextNode.next;
i++;
}
while(nextNode != null){
preNode = preNode.next;
nextNode = nextNode.next;
}
System.out.println(preNode.data);
return preNode;
}
//反转列表
public void reverseLink(){
Node reverseNode = head;
Node nextNode = null;
Node pNode = head;
Node preNode = null;
while(pNode != null){
nextNode = pNode.next;
if(nextNode == null)
reverseNode = pNode;
pNode.next = preNode;
preNode = pNode;
pNode = nextNode;
this.head = reverseNode;
}
}
public void printReverseLink(Node pNode){
if(pNode!= null){
//pNode = pNode.next;
printReverseLink(pNode.next);
System.out.print(pNode.data + "\t");
}
System.out.println();
}
//找到列表中间的节点
public void findMidNode(){
Node preNode = head;
Node nextNode = head;
while(preNode != null && preNode.next != null && preNode.next.next != null){
preNode = preNode.next.next;
nextNode = nextNode.next;
}
System.out.println("the data of the mid is : "+ nextNode.data);
if(preNode.next != null){
System.out.println("the data of the mid is : "+ nextNode.next.data);
}
}
//判断列表中是否有环路
public boolean isLoop(){
Node fast = head;
Node slow = head;
if(fast == null){
return false;
}
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow){
return true;
}
}
return !(fast == null || fast.next == null);
}
//在不知道头指针的情况下,删除该节点
public boolean deleteNode(Node node){
if(node == null || node.next ==null){
return false;
}
Node nextNode = node.next;
int temp = nextNode.data;
node.data = nextNode.data;
nextNode.data = temp;
node.next = node.next.next;
return true;
}
public static void main(String[] args) {
MyLink ml = new MyLink();
ml.addNode(1);
ml.addNode(3);
ml.addNode(5);
ml.addNode(2);
ml.addNode(4);
ml.printLink();
ml.orderLink();
ml.printLink();
ml.deleteNode(1);
ml.printLink();
ml.addNode(4);
ml.printLink();
ml.orderLink();
ml.printLink();
ml.delDup();
ml.printLink();
ml.addNode(6);
ml.addNode(7);
Node delete = ml.addNode(8);
ml.addNode(9);
ml.printLink();
/*ml.findBackthData(2);
ml.printLink();
//ml.reverseLink();
//ml.printLink();
ml.printReverseLink(MyLink.head);*/
ml.findMidNode();
/*ml.deleteNode(1);
ml.printLink();
ml.findMidNode();*/
//Node node = new Node(8);
ml.printLink();
ml.deleteNode(delete);
ml.printLink();
}
}