四种语言刷算法之删除链表的倒数第 N 个结点
力扣19. 删除链表的倒数第 N 个结点
1、C
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
if(head==NULL)return NULL;
struct ListNode*p = NULL;
struct ListNode *q = head;
struct ListNode *r = head;
int count = 1;
while(r->next!=NULL){
if(count<n){
r = r->next;
count++;
}
else{
r = r->next;
p = q;
q = q->next;
}
}
if(count<n)return NULL;
if(p==NULL){
p = head->next;
free(head);
return p;
}
p->next = q->next;
free(q);
return head;
}
2、C++
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { if(head==nullptr)return nullptr; ListNode *p = nullptr; ListNode *q = head; ListNode *r = head; int count = 1; while(r->next!=nullptr){ if(count<n){ r = r->next; count++; } else{ r = r->next; p = q; q = q->next; } } if(count<n)return nullptr; if(p==nullptr){ p = q; q = q->next; delete p; return q; } p->next = q->next; delete q; return head; } };
3、JAVA
/** * 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 p = null; ListNode q = head; ListNode r = head; int count = 1; while(r.next!=null){ if(count<n){ r = r.next; count++; } else{ r = r.next; p = q; q = q.next; } } if(count<n)return null; if(p==null){ return head.next; } p.next = q.next; return head; } }
4、Python
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ if(head is None): return None p = None q = head r = head count = 1 while(r.next is not None): if count<n: r = r.next count += 1 else: r = r.next p = q q = q.next if count<n: return None if p is None: return head.next p.next = q.next return head