首页 > 代码库 > 【LeetCode】19. Remove Nth Node From End of List
【LeetCode】19. Remove Nth Node From End of List
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5.
题意:给出一个链表,删除倒数第n个节点
刚在书上见过这个题,思路是用双指针,p1,p2,先让p2走n步,然后p1,p2一块走,当p2停止的时候,
p1->next正好指向要删除的节点,不过要注意:
当p2停止的时候,n还没变为0,这时候要验证n的值,当n>0时候,p1指向的节点就是要删除的节点
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * struct ListNode *next; 6 * }; 7 */ 8 struct ListNode* removeNthFromEnd(struct ListNode* head, int n) { 9 if(head==NULL) 10 return head; 11 struct ListNode *p1,*p2,*tmp; 12 p1=head; 13 p2=head; 14 while(n>0&&p2->next!=NULL){ 15 p2=p2->next; 16 n--; 17 } 18 if(n>0){ 19 tmp=p1; 20 head=p1->next; 21 free(tmp); 22 } 23 else 24 { 25 while(p2->next!=NULL){ 26 p2=p2->next; 27 p1=p1->next; 28 } 29 tmp=p1->next; 30 if(tmp!=NULL){ 31 p1->next=tmp->next; 32 free(tmp); 33 } 34 } 35 return head; 36 }
【LeetCode】19. Remove Nth Node From End of List
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。