链表,删除链表倒数第N个节点
1. 题目描述
难易度:中等
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list
2. 思路分析
- 定义快慢指针,slow和fast
- 先让快指针走n步
- 快慢指针同时走,直到链表结尾
- 具体细节看代码注释
3. 代码演示
/**
* @Description TODO
* @Author YunShuaiWei
* @Date 2020/5/7 14:32
* @Version
**/
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
//若头节点为空则直接返回
if (head == null) {
return null;
}
//定义快慢指针
ListNode slow = head;
ListNode fast = head;
while (n > 0) {
fast = fast.next;
n--;
}
//当fast==null则表示n等于链表长度,则将头节点指向第二个节点返回
if (fast == null) {
return head.next;
}
//快慢指针各走一步,若fast的next等于null,则此时fast指向最后一个节点
while (fast.next != null) {
slow = slow.next;
fast = fast.next;
}
//删除节点
if (slow != null) {
slow.next = slow.next.next;
}
return head;
}
}