leetcode 19

时间:2022-04-25 17:14:26

leetcode 19

最开始用一般的方法,首先遍历链表求出长度,进而求出需要删除节点的位置,最后进行节点的删除。

代码如下:

 /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* h = head;
int length = ;
while(h != NULL)
{
length ++;
h = h->next;
}
int s = length - n;
if(s == )
{
return head->next;
}
ListNode* hh = head;
s--;
while(s > )
{
hh= hh->next;
s--;
}
h = hh->next;
hh->next = h->next;
return head;
}
};

之后学习了别人更加巧妙的方法:

同时初始化两个指向头结点的指针,一个先向后走n步,然后两个指针同时向后移动,

当第一个指针到达终点的时候第二个指针的位置就是要删除的结点。

 /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* head1 = head;
ListNode* head2 = head;
while(n > )
{
head1 = head1->next;
n --;
}
if(head1 == NULL)
{
return head->next;
}
while(head1->next != NULL)
{
head1 = head1->next;
head2 = head2->next;
}
head1 = head2->next;
head2->next = head1->next;
return head;
}
};

重写后提交竟然是100%~

leetcode 19