呃呃,一个单向链表,给定一个K,实现k+1和K的反转,这个只是反转一次已经降低难度了,貌似没打算考我递归
我擦嘞,当时竟然没考虑到K-1,你是怎么一回事啊,提示好多次了,好多问题买考虑全
可能需要我考虑一下几点
1.链表长度小于传过来的参数K
2.链表为空
3.k参数不合法
public static class ListNode {
int data;
ListNode next;
public ListNode(int value, ListNode next) {
this.data = value;
this.next = next;
}
}
public static int showListValueAndSize(ListNode head) {
if(head == null){
return 0;
}
int count = 1;
while (head.next!=null) {
count++;
System.out.println("当前节点值为" + head.data);
head = head.next;
}
System.out.println("尾节点没有下一个,尾节点是"+head.data);
return count;
}
public static ListNode findKthNodeFromEnd(ListNode head, int k) {
if (head == null){
throw new RuntimeException("待查找的链表不能为空");
}
if (k <= 0){
throw new RuntimeException("输入的位置数字不合法");
}
int size = showListValueAndSize(head);
if(k>size) {
throw new RuntimeException("k="+k+"的值大于链表的个数"+size+"位置数字不合法");
}
//指向当前节点
ListNode ahead = head;
//被切换的值,并没有移动指针只是换值
int temp;
int count = 0;
while (ahead.next != null) {
if(count == k-1){
temp = ahead.data;
ahead.data = ahead.next.data;
ahead.next.data = temp;
}
count++;
ahead = ahead.next;
}
return head;
}