[LeetCode]Remove Nth Node From End of List

来源:互联网 发布:哪个论坛源码好移动版 编辑:程序博客网 时间:2024/06/16 00:11
解题思路:
就提一点。一般要删除一个node,我们最好知道它前一个 preNode。这就存在一个问题,如果要删除head,用之前的方法肯定出错。
办法:在head前加一个 新的空node。

边界条件:head不为空
前条件:length, front->next = head
不变式:遍历list到想要删除的prenode 

/** * 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) {        if (head == NULL)            return NULL;        ListNode* front = new ListNode(0);        front->next = head;        ListNode* cur = front;        int length = 0;        while(cur != NULL){            length ++;            cur = cur->next;        }        int deleteIndex = length - n;        cur = front;        while ( --deleteIndex  ){            cur = cur->next;        }        ListNode* temp = cur->next;        cur->next = temp->next;        free(temp);        return front->next;    }};


0 0
原创粉丝点击