// 02-线性结构3 Reversing Linked List
import java.util.Scanner;
class Node{
String address;
String data;
String Nextaddress;
Node next;
public Node() {
this.next = null;
}
public Node(String x, String y, String z) {
this.address = x;
this.data = y;
this.Nextaddress = z;
}
}
public class Main{
static Node creat(String head, String[][] a) {
String p = head;
Node n = new Node();
Node l = n;
while(p.equals("-1") == false) {
for(int i = 0; i < a.length; i ++) {
if(p.equals(a[i][0])) {
p = a[i][2];
Node newnode = new Node(a[i][0], a[i][1], a[i][2]);
n.next = newnode;
n = n.next;
break;
}
}
}
//System.out.println("链表创建完成。");
return l;
}
static Node reverse(int k, Node head) {
Node rhead = head;
if(k == 1) {
return head;
}
else {
int i = 0;
while(head.next != null) {
i ++;
head = head.next;
}
//System.out.println(i);
head = rhead;
Node pre = head.next;
Node pcur = pre.next;
int reverse = 1;
while(reverse <= i / k && pcur != null) {
Node n = head;
for(int x = 0; x < k + 1; x ++) {
n = n.next;
}
for(int c = 0; c < k - 1; c ++){
if(pcur.next != null) {
pre.next = pcur.next;
pcur.next = head.next;
head.next = pcur;
pcur = pre.next;
}
else {
pre.next = null;
pcur.next = head.next;
head.next = pcur;
pcur = pre.next;
}
}
if(pre.next != null) {
head = pre;
pre = head.next;
pcur = pre.next;
reverse ++;
}
}
head = rhead.next;
while(head.next != null) {
head.Nextaddress = head.next.address;
head = head.next;
}
if(i % k == 0) {
pre.Nextaddress = "-1";
}
return rhead;
}
}
static void print(Node n) {
Node l = n;
while(l.next != null) {
System.out.println(l.next.address + " " + l.next.data + " " + l.next.Nextaddress);
l = l.next;
}
/*if(l.address != null) {
System.out.println(l.address + l.data + l.Nextaddress);
}*/
}
/*static int scanner() {
int x = -1;
Scanner s = new Scanner(System.in);
if(s.hasNextInt()) {
x = s.nextInt();
}
return x;
}*/
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
String head = s.next();
int n = s.nextInt();
int k = s.nextInt();
String[][] a = new String[n][3];
for(int i = 0; i < n; i ++) {
for(int j = 0; j < 3; j ++) {
a[i][j] = s.next();
//System.out.println(a[i][j]);
}
}
/*for(int i = 0; i < a.length; i ++) {
System.out.println(a[i][1]);
}*/
Node list = creat(head, a);
//print(list);
Node rlist = reverse(k, list);
print(rlist);
}
}
02-线性结构3 Reversing Linked List
最新推荐文章于 2024-07-13 13:55:40 发布