下面是链表程序,我试图通过k节点反转链表。 k是用户提供的输入。但问题是低于逻辑只会以相反的顺序返回前三个节点。
package p;
import java.util.Scanner;
public class LinkedListDemoReverseKNode {
class MyList {
public int info;
public MyList link;
public MyList(){
this.link = null;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
MyList s = new MyList();
System.out.println("enter value :");
s.info = sc.nextInt();
Character ch = null;
MyList t = s;
MyList commonNode = null;
while (true) {
System.out.println("to create node press Y else N ");
ch = sc.next().charAt(0);
if (ch == 'n' || ch == 'N') {
break;
}
s.link = new MyList();
System.out.println("enter value for the node :");
s.link.info = sc.nextInt();
s = s.link;
}
// Reverse the linked list k-node :
s = t;
LinkedListDemoReverseKNode linkedListDemo3 = new LinkedListDemoReverseKNode();
MyList head = linkedListDemo3.reverseLinkedListKNode(s, 3);
while (head != null) {
System.out.println("info :: " + head.info);
head = head.link;
}
}
private MyList reverseLinkedListKNode(MyList head, int k) {
MyList s = head;
MyList prev = null;
MyList next = null;
int count = 0;
while (count < k && s != null) {
next = s.link;
s.link = prev;
prev = s;
s = next;
count++;
}
if (next != null)
s.link = reverseLinkedListKNode(next, k);
return prev;
}
}
答案 0 :(得分:0)
// Reverse the linked list k-node :
s = t;
LinkedListDemoReverseKNode linkedListDemo3 = new LinkedListDemoReverseKNode();
MyList head = linkedListDemo3.reverseLinkedListKNode(s, 3);
while (head != null) {
System.out.println("info :: " + head.info);
head = head.link;
在这行代码中,它说: MyList head = linkedlistDemo3.reverselinkedlistNode(s,3) 尝试改变它所说的位置(s,3)
答案 1 :(得分:0)
如果你看一下代码的这一部分MyList head = linkedListDemo3.reverseLinkedListKNode(s, 3);
,你就要告诉它要反转链表中的三个第一个节点。
该方法要求反转k
个节点的数量:
private MyList reverseLinkedListKNode(MyList head, int k)
您可以将k
设置为列表中的总节点,以反转所有节点,或反转任意数量的节点。
答案 2 :(得分:-1)
您可以简单地使用Collections.reverse ...