package demo2;
class Node {//节点类
int data;
Node next=null;
public Node(int data) {
this.data = data;
}
}
package demo2;
public class MyLinkedList {//单链表类
public Node head=null;
public void addNode(int d){
Node newNode=new Node(d);
if(head==null){
head=newNode;
return;
}
Node tmp=head;
while (tmp.next!=null){
tmp=tmp.next;
}
tmp.next=newNode;
}
public void printList(){
Node tmp=head;
while (tmp!=null){
System.out.println(tmp.data);
tmp=tmp.next;
}
}
public int length(){
int length=0;
Node tmp=head;
while(tmp!=null){
tmp=tmp.next;
length++;
}
return length;
}
public Node Find(int k){//查找倒数第K个节点
if(k<=0||k>this.length())
return null;
Node p1=head;
Node p2=head;
for(int i=0;i<k-1;i++){
if(p1.next!=null){
p1=p1.next;
}else{
return null;
}
}
while (p1.next!=null){
p1=p1.next;
p2=p2.next;
}
return p2;
}
public Node Reverse(){//对链表进行反转
Node pReverseHead=head;
Node pNode=head;
Node pPre=null;
while(pNode!=null){
Node pNext=pNode.next;
if(pNext==null){
pReverseHead=pNode;
}
pNode.next=pPre;
pNode=pNext;
pPre=pNode;
}
return pReverseHead;
}
}
package demo2;
public class TestMyLinkedList {//测试类
public static void main(String args[]){
MyLinkedList list=new MyLinkedList();
list.addNode(5);
list.addNode(4);
list.addNode(3);
list.addNode(2);
list.addNode(1);
list.printList();
System.out.println("===================");
System.out.println(list.Find(6).data);//查找倒数第K个结点
System.out.println("===================");
System.out.println(list.Reverse().data);//对链表进行反转输出新链表的头结点
}
}
结果:
因篇幅问题不能全部显示,请点此查看更多更全内容