Remove Nth Node From End of List

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.

考虑用双链表,先让第一个链表走n-1步,然后让第二个链表从头开始两个链表一起走,直到第一个走到头,此时第二个链表刚好走到要删除的节点,保存删除节点的上一个节点即可,但是要考虑边界条件,这里考虑了n输入不合法的问题

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode *removeNthFromEnd(struct ListNode *head, int n) {
    if(head == NULL || n<= 0) return NULL;
    struct ListNode *pre = NULL;
    struct ListNode *p = head;
    struct ListNode *q = head;
    n--;
    while(p->next != NULL && n>0){
        p = p->next;
        n--;
    }
    if(n>0) return NULL;
    while(p->next != NULL){
        pre = q;
        p = p->next;
        q = q->next;
    }
    if(pre == NULL){
        head = q->next;
    }else{
        pre->next = q->next;
    }
    return head;
}

看到还有一种方法是走到要删除的节点时,将它的下一个节点值复制到当前节点,然后删除它的下一个节点,这种方法也可以。但是要判断倒数第一个节点的问题。

posted @ 2015-03-26 21:09  hongchun_z  阅读(104)  评论(0编辑  收藏  举报