给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
主要思路:快慢指针,快指针前进n,快满指针开始同时移动,快指针到表尾,慢指针到倒数第n个节点,slow = slow.next 即可。
/**
* 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) {
ListNode dummy = new ListNode(0, head);
ListNode first = head;
ListNode second = dummy;
for (int i = 0; i < n; ++i) {
first = first.next;
}
while (first != null) {
first = first.next;
second = second.next;
}
second.next = second.next.next;
ListNode ans = dummy.next;
return ans;
}
}
反转链表
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null || head.next == null){
return head;
}
ListNode prev = null,current = head;
while(current != null){
//临时变量保存下一节点
ListNode tmp = current.next;
//反转,当前节点指向前一节点
current.next = prev;
//prev节点前移
prev = current;
//当前节点前移
current = tmp;
}
return prev;
}
}