给你一个链表,删除链表的倒数第 n
个结点,并且返回链表的头结点。
- /**
- * 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 ListNode removeNthFromEnd(ListNode head, int n) {
- int nums=0;
- ListNode p=head;
- while(p!=null){
- nums++;
- p=p.next;
- }
-
- if(nums == 1)
- return null;
- if(nums == n)
- return head.next;
- n=nums-n;
- p=head;
- ListNode q=head.next;
- while(q!=null){
- n--;
- if(n==0){
- p.next=q.next;
- break;
- }
- p=p.next;
- q=q.next;
- }
- return head;
- }
- }
书店店员有一张链表形式的书单,每个节点代表一本书,节点中的值表示书的编号。为更方便整理书架,店员需要将书单倒过来排列,就可以从最后一本书开始整理,逐一将书放回到书架上。请倒序返回这个书单链表。
- /**
- * 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) {
- // List<Integer> list = new ArrayList<>();
- // ListNode q=head;
-
- // while(q != null){
- // list.add(q.val);
- // q=q.next;
- // }
- // int n=list.size();
- // int[] a =new int[n];
- // int j=0;
- // for(int i=n-1;i>=0;i--){
- // a[j++]=list.get(i);
- // }
-
- // return a;
- LinkedList<Integer> stack = new LinkedList<Integer>();
- while(head != null) {
- stack.addLast(head.val);
- head = head.next;
- }
- int[] res = new int[stack.size()];
- for(int i = 0; i < res.length; i++)
- res[i] = stack.removeLast();
- return res;
- }
- }