【leetcode】19. Remove Nth Node From End of List

来源:互联网 发布:当代大学生创业数据 编辑:程序博客网 时间:2024/06/12 00:48
/** * 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. * * Note: * Given n will always be valid. * Try to do this in one pass. */#include <iostream>#include <string>#include <vector>using namespace std;struct ListNode {    int val;    ListNode *next;    ListNode(int x) : val(x), next(NULL) {} };ListNode* createList(ListNode*head, int num){    ListNode* pl = head;    ListNode* node = new ListNode(num);    if (pl == NULL)    {        head = node;    }    else    {        while (pl->next != NULL)        {            pl = pl->next;        }        pl->next = node;    }    return head;}ListNode* removeNthFromEnd(ListNode* head, int n) {    ListNode *ph, *pre, *back, *tmp;    ph = pre = back = tmp = head;    for (int i = 1; i < n; i++)    {        ph = ph->next;    }    while (ph->next != NULL)    {        pre = back;        back = back->next;        ph = ph->next;    }    tmp = pre->next;    pre->next = back->next;    free(tmp);    return head;}//leetcode 利用二级指针删除ListNode* removeNthFromEnd1(ListNode* head, int n){    ListNode *ph, *tmp;    ph = tmp = head;    ListNode **back = &head;    for (int i = 1; i < n; i++)    {        ph = ph->next;    }    while (ph->next != NULL)    {        back = &((*back)->next);        ph = ph->next;    }    tmp = *back;    *back = (*back)->next;    free(tmp);    return head;}int main(){    int arr[] = { 1, 2, 3, 4, 5 };    ListNode*head = NULL;    for (int i = 0; i < 5; i++)    {        head = createList(head, arr[i]);    }    removeNthFromEnd1(head, 2);    system("pause");    return 0;}
0 0
原创粉丝点击