实现反转单向链表和双向链表的函数。
如 1->2->3 反转后变成 3->2->1。
第一行一个整数 n,表示单链表的长度。
第二行 n 个整数 val 表示单链表的各个节点。
第三行一个整数 m,表示双链表的长度。
第四行 m 个整数 val 表示双链表的各个节点。
在给定的函数内返回相应链表的头指针。
3 1 2 3 4 1 2 3 4
3 2 1 4 3 2 1
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class Main{
public static class ListNode{
int var;
ListNode next;
ListNode(int var){
this.var = var;
}
}
public static class DListNode{
int var;
DListNode next;
DListNode prev;
DListNode(int var){
this.var = var;
}
}
public static ListNode createListNode(int N, String[] strs){
//ListNode head = new ListNode(0); //don't init it as 0, we'd better use first value of the array to initialize head
ListNode head = new ListNode(Integer.valueOf(strs[0]));
ListNode tail = head;
for(int i=1;i<N;i++){
ListNode newNode = new ListNode(Integer.valueOf(strs[i]));
tail.next = newNode;
tail = tail.next;
}
return head;
}
public static DListNode createDListNode(int N, String[] strs){
DListNode dListHead = new DListNode(Integer.valueOf(strs[0]));
DListNode curDListNode = dListHead;
for(int i=1;i<N;i++){
DListNode newDListNode = new DListNode(Integer.valueOf(strs[i]));
curDListNode.next = newDListNode;
newDListNode.prev = curDListNode;
curDListNode = curDListNode.next;
}
return dListHead;
}
public static ListNode reverseList(ListNode head){
ListNode prev = null;
ListNode next;
ListNode cur = head;
while(cur != null){
next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
return prev;
}
public static DListNode reverseDList(DListNode head){
DListNode prev = null;
DListNode next;
DListNode cur = head;
while(cur != null){
next = cur.next;
cur.next = prev;
cur.prev = next;
prev = cur;
cur = next;
}
return prev;
}
public static void show(ListNode head){
while(head!=null){
System.out.print(head.var + " ");
head = head.next;
}
System.out.println();
}
public static void show(DListNode head){
while(head!=null){
System.out.print(head.var + " ");
head = head.next;
}
System.out.println();
}
public static void main(String[] argv) throws FileNotFoundException {
Scanner sc = new Scanner(System.in);
//Scanner sc = new Scanner(new BufferedReader(new FileReader("src/ReverseListInput.txt")));
String strFirstLine = sc.nextLine();
int N = Integer.valueOf(strFirstLine);
String strSecondLine = sc.nextLine();
String strSecondLineArray[] = strSecondLine.split(" ");
ListNode listNodeHead = createListNode(N,strSecondLineArray);
String strThirdLine = sc.nextLine();
int M = Integer.valueOf(strThirdLine);
String strFourthLine = sc.nextLine();
String strFourthLineArray[] = strFourthLine.split(" ");
show(reverseList(listNodeHead));
DListNode dListHead = createDListNode(M,strFourthLineArray);
show(reverseDList(dListHead));
}
}