19、Remove Nth Node From End of List

来源:互联网 发布:linux ping 100个包 编辑:程序博客网 时间:2024/04/29 16:58

Given a linked list, remove the nth node from the end of list and return its head.

For example,

Given a linked list, remove the nth node from the end of list and return its head.

For example,

Note:
Given n will always be valid.
Try to do this in one pass.

Linked List Two Pointers
ListNode *removeNthFromEnd(ListNode *head, int n) {        //此题要求比遍历一遍搞定,需要一个指针来指向删除节点的前面节点,对于删除头结点的情况需要特殊考虑, p -> next和q-> next节点的关系需要搞清楚        ListNode *p = head, *q = head;        while (n--)            q = q -> next;        if (q == NULL)            return p -> next;        while (q -> next)        {            p = p -> next;            q = q -> next;        }        p -> next = p -> next -> next;        return head;    }


0 0
原创粉丝点击