首先链表类先声明
Definition for singly-linked list.
public class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
1、建立一个头结点,并指向原本链表的的头
ListNode tempNode=new ListNode(0);
tempNode.next=head;
2、定义一个指针,指向所需要的节点
ListNode temp=tempNode;
反转链表
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
}
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null)
return l2;
if (l2 == null)
return l1;
ListNode head = new ListNode();
ListNode p = head;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
p.next = l1;
l1 = l1.next;
} else {
p.next = l2;
l2 = l2.next;
}
p = p.next;
}
if (l1 == null) {
p.next = l2;
}
if (l2 == null) {
p.next = l1;
}
return head.next;
}
}
import java.util.Scanner;
import java.util.Vector;
import java.util.ArrayList;
import java.util.List;
public class Main{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int start = in.nextInt();
int n = in.nextInt();
testtemp arr[] = new testtemp[100001];
for(int i=0;i
}
List
for(;arr[start].next!=-1;start=arr[start].next){
list.add(start);
}
list.add(start);
int i=0;int j=list.size()-1;
while(i<=j){//用两个指针一个从前一个从后面遍历
if(j==list.size()-1){
System.out.printf(“%05d %d “, list.get(j), arr[list.get(j)].num);
j—;
}else{
System.out.printf(“%05d\n”, list.get(j));
System.out.printf(“%05d %d “, list.get(j), arr[list.get(j)].num);
j—;
}
if(i<=j){
System.out.printf(“%05d\n”, list.get(i));
System.out.printf(“%05d %d “, list.get(i), arr[list.get(i)].num);
i++;
}
if(i>j){
System.out.printf(“-1”);
}
}
}
}
class testtemp{
public int num;
public int next;
public testtemp(int num, int next){
this.num = num;
this.next = next;
}
}
