字符串的反转
递归法实现单链表反转
public class ReverseList {
public static void main(String[] args){
Node linkNode=new Node();
linkNode.data=1;
Node linkNode2=new Node();
linkNode2.data=2;
Node linkNode3=new Node();
linkNode3.data=3;
Node linkNode4=new Node();
linkNode4.data=4;
Node linkNode5=new Node();
linkNode5.data=5;
Node linkNode6=new Node();
linkNode6.data=6;
linkNode.next=linkNode2;
linkNode2.next=linkNode3;
linkNode3.next=linkNode4;
linkNode4.next=linkNode5;
linkNode5.next=linkNode6;
//链表翻转递归
// Node newHead=reverse(linkNode);
// //遍历
// Node node=newHead;
// while (node !=null){
// System.out.print(node.data);
// node=node.next;
// }
//链表翻转遍历
Node newHead=reverseList(linkNode);
//遍历
Node node=newHead;
while (node !=null){
System.out.print(node.data);
node=node.next;
}
//从尾到头输出单链表
// printListReversely(linkNode);
//判断单链表中是否有环
// linkNode6.next=linkNode;//形成环
// System.out.print(IsLoop(linkNode));
//查找倒数第三个元素输出其值
// System.out.print(findElem(linkNode,3).data);
}
//递归法实现单链表的反转
private static Node reverse(Node head) {
if(head==null || head.next==null){
return head;
}
Node temp=head.next;
Node newHead=reverse(head.next);
temp.next=head;
head.next=null;
return newHead;
}
//从尾到头输出单链表,递归
public static void printListReversely(Node pListHead){
if(pListHead!=null){
printListReversely(pListHead.next);
System.out.print(pListHead.data);
}
}
}
class Node{
Integer data;
Node next;
}
遍历法实现单链表反转
//遍历法实现实现单链表反转
private static Node reverseList(Node node){
Node pre=null;
Node next=null;
while (node!=null){
next=node.next;
node.next=pre;
pre=node;
node=next;
}
return pre;
}
检测单链表是否有环
//检测一个单链表是否有环
public static Boolean IsLoop(Node head){
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);
}
找出单链表倒数第k个元素
//找出单链表中倒数第K个元素
public static Node findElem(Node head,int k){
//判断k的值是否越界
// if(k<1 || k>this.length()){
// return null;
// }
Node p1=head;
Node p2=head;
for(int i=0;i<k-1;i++){
p1=p1.next;
}
while (p1.next!=null){
p1=p1.next;
p2=p2.next;
}
return p2;
}