原题地址:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
题目描述:
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
进阶:
你能尝试使用一趟扫描实现吗?
解题方案:
这道题要求遍历一遍,思路就是使用两个指针pre和cur,中间间隔为n+1,这样当pre指向尾指针后面的null时,删除cur下一个节点即可。需要注意的是删除头指针的情况,即pre还没有移动到和cur隔n+1个位置时就已经到null的情况。
代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode pre = head, cur = head;
int count = 0;
while(pre != null)
{
if(count == n + 1)
break;
pre = pre.next;
count ++;
}
if(pre == null && count != n + 1)
{
head = head.next;
return head;
}
while(pre != null)
{
pre = pre.next;
cur = cur.next;
}
cur.next = cur.next.next;
return head;
}
}