给定一个链表,删除链表的倒数第 n 个节点并返回头结点。
例如,
给定一个链表: 1->2->3->4->5, 并且 n = 2.
当删除了倒数第二个节点后链表变成了 1->2->3->5.
详见:https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/
思路:设置两个指针first跟second。first指针先移动n步,若此时first指针为空,则表示要删除的是头节点,此时直接返回head->next即可。如果first指针不为空,则将两个指针一起移动,直到first指针指向最后一个节点,令second->next=second->next->next即可删除第你n个节点。
实现语言:Java
/**
* 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) {
if(head==null||head.next==null){
return null;
}
ListNode first=head,second=head;
for(int i=0;i<n;++i){
first=first.next;
}
if(first==null){
return head.next;
}
while(first.next!=null){
first=first.next;
second=second.next;
}
second.next=second.next.next;
return head;
}
}
参考:https://blog.csdn.net/yao_wust/article/details/41242805