[LeetCode-19] Remove Nth Node From End of List(删除倒数第N个节点)

来源:互联网 发布:虚拟专用网络 编辑:程序博客网 时间:2024/05/16 12:45

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.

struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {    if(!head)        return NULL;    if(0 == n) {        return head;    }    struct ListNode *p = head;    struct ListNode *free_node = NULL;    int ListNodeLen = 0;    /*1.链表长度计算*/    while(p) {        ListNodeLen ++;        p = p->next;    }    if(n > ListNodeLen)        return head;    p = head;//  printf("[%d] ListNodeLen: %d\n",__LINE__,ListNodeLen);    /*2.第一个节点*/    if(n == ListNodeLen) { /*第一个节点*/        head = p->next;        free(p);    //  printf("[%d] ListNodeLen: %d\n",__LINE__,ListNodeLen);        return head;    }//  printf("[%d] ListNodeLen: %d\n",__LINE__,ListNodeLen);    int count = 0;    /*3.定位到倒数第n+1个位置,删除第n个节点*/    while(1) {        if(count == (ListNodeLen-n-1)) {  /*定位到倒数第n+1个位置*/             free_node = p->next;             p->next = p->next->next;             free(free_node);             break;        }        p = p->next;        count++;    }    return head;}
0 0
原创粉丝点击