美文网首页
19. Remove Nth Node From End of

19. Remove Nth Node From End of

作者: gpfworld | 来源:发表于2018-12-10 15:17 被阅读0次

题目描述:

https://leetcode.com/problems/remove-nth-node-from-end-of-list/

解决方案:

https://leetcode.com/problems/remove-nth-node-from-end-of-list/solution/

mycode(c++):

/**
 * 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 * tp_head = head;
        ListNode * pre = head;
        while( n > 0 ){
            tp_head = tp_head->next;
            n--;
        }
        if(tp_head==NULL)
            if( n ==1 )
                return NULL;
            else{
                pre = pre->next;
                return pre;
            }
        while(tp_head->next!=NULL){
            tp_head= tp_head->next;
            pre = pre->next;
        }
        pre->next = pre->next->next;
        return head;
    }
};

心得:

凡是涉及到链表删除问题,都需要考虑一下几种情况
1.删除链表的首节点
2.删除链表尾节点
3.删除链表中间节点
4.删除节点后链表变为空链表
还有就是类似问题,采用双指针,达到链表的一次遍历解决问题。

相关文章

网友评论

      本文标题:19. Remove Nth Node From End of

      本文链接:https://www.haomeiwen.com/subject/worrhqtx.html