最开始用一般的方法,首先遍历链表求出长度,进而求出需要删除节点的位置,最后进行节点的删除。
代码如下:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* removeNthFromEnd(ListNode* head, int n) { 12 ListNode* h = head; 13 int length = 0; 14 while(h != NULL) 15 { 16 length ++; 17 h = h->next; 18 } 19 int s = length - n; 20 if(s == 0) 21 { 22 return head->next; 23 } 24 ListNode* hh = head; 25 s--; 26 while(s > 0) 27 { 28 hh= hh->next; 29 s--; 30 } 31 h = hh->next; 32 hh->next = h->next; 33 return head; 34 } 35 };
之后学习了别人更加巧妙的方法:
同时初始化两个指向头结点的指针,一个先向后走n步,然后两个指针同时向后移动,
当第一个指针到达终点的时候第二个指针的位置就是要删除的结点。
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* removeNthFromEnd(ListNode* head, int n) { 12 ListNode* head1 = head; 13 ListNode* head2 = head; 14 while(n > 0) 15 { 16 head1 = head1->next; 17 n --; 18 } 19 if(head1 == NULL) 20 { 21 return head->next; 22 } 23 while(head1->next != NULL) 24 { 25 head1 = head1->next; 26 head2 = head2->next; 27 } 28 head1 = head2->next; 29 head2->next = head1->next; 30 return head; 31 } 32 };
重写后提交竟然是100%~