LCR 123. 图书整理 I
题目描述
书店店员有一张链表形式的书单,每个节点代表一本书,节点中的值表示书的编号。为更方便整理书架,店员需要将书单倒过来排列,就可以从最后一本书开始整理,逐一将书放回到书架上。请倒序返回这个书单链表。
示例 1:
输入:head = [3,6,4,1]
输出:[1,4,6,3]
提示:
0 <= 链表长度 <= 10000
代码展示
逆转链表法
顾名思义,先逆转链表,再输出为数组。
/**
* 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; }
* }
*/
class Solution {
public int[] reverseBookList(ListNode head) {
//逆转链表头
ListNode node = new ListNode();
ListNode p = head;
int num = 0;
//逆转链表
while(p!=null){
ListNode next = p.next;
p.next = node.next;
node.next = p;
p = next;
num++;
}
ListNode q = node.next;
int[] result = new int[num];
int a = 0;
//链表转为数组
while(q!=null){
result[a++] = q.val;
q = q.next;
}
return result;
}
}
栈方法
依次遍历链表入栈,再出栈到数组,就可以实现逆转了。
/**
* 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; }
* }
*/
class Solution {
public int[] reverseBookList(ListNode head) {
Stack<Integer> stack = new Stack<Integer>();
ListNode p = head;
while(p!=null){
stack.push(p.val);
p=p.next;
}
int[] result = new int[stack.size()];
int a = 0;
while(!stack.isEmpty()){
result[a++] = stack.pop();
}
return result;
}
}
倒序插入法
正序遍历链表,从数组的最后一位倒序开始插入。
/**
* 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; }
* }
*/
class Solution {
public int[] reverseBookList(ListNode head) {
int len = getLength(head);
int i = len-1;
int[] result= new int[len];
ListNode p = head;
while(i>=0){
result[i] = p.val;
p = p.next;
i--;
}
return result;
}
public int getLength(ListNode head){
ListNode node = head;
int count = 0;
while(node!=null){
count++;
node = node.next;
}
return count;
}
}
ArrayList方法
与Stack方法思想一致,只不过用的类型不一样。而且ArrayList需要从最后面进行向前遍历,还不如stack直接顺序遍历方便。了解一下即可。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public int[] reversePrint(ListNode head) {
ArrayList<Integer> list = new ArrayList<Integer>();
ListNode p = head;
int n = 0;
while(p!=null){
list.add(p.val);
p = p.next;
n++;
}
int[] arr = new int[n];
for(int i = 0;i<n;i++){
arr[i] = list.get(n-i-1);
}
return arr;
}
}