链表反转
import java.util.Scanner;
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public class lianbiao {
public static ListNode builderHelper(ListNode pNode,int num) {
if(pNode==null) {
return new ListNode(num);
}
pNode.next=builderHelper(pNode.next,num);
return pNode;
}
public static ListNode builder(int[] nums) {
ListNode head = null;
for(int num:nums) {
if(head==null) {
head = new ListNode(num);
continue;
}
builderHelper(head,num);
}
return head;
}
public static ListNode kNode(ListNode head,int k) {
ListNode p1=head;
ListNode p2=head;
while(k-->0) {
p2=p2.next;
}
while(p2!=null) {
p1=p1.next;
p2=p2.next;
}
return p1;
}
public static ListNode reverse(ListNode head) {
if(head.next==null) return head;
ListNode last = reverse(head.next);
head.next.next=head;
head.next=null;
return last;
}
public static ListNode successor = null;
public static ListNode reverseN(ListNode head, int n) {
if(n==1) {
successor = head.next;
return head;
}
ListNode last = reverseN(head.next,n-1);
head.next.next=head;
head.next=successor;
return last;
}
public static ListNode reverseMN(ListNode head, int m, int n) {
if(m==1) {
return reverseN(head, n);
}
head.next=reverseMN(head.next,m-1,n-1);
return head;
}
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
while(in.hasNext()) {
String[] str = in.nextLine().split(" ");
int k = Integer.parseInt(in.nextLine());
int[] nums = new int[str.length];
int i=0;
for(String s:str) {
nums[i++]=Integer.parseInt(s);
}
ListNode node = builder(nums);
ListNode mnnode= reverseMN(node,2,4);
while(mnnode!=null) {
System.out.print(mnnode.val +" ");
mnnode=mnnode.next;
}
}
}
}