首页 > 其他 > 详细

Remove Nth Node From End of List

时间:2015-03-26 22:57:00      阅读:204      评论:0      收藏:0      [点我收藏+]

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;
}

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

Remove Nth Node From End of List

原文:http://www.cnblogs.com/zhhc/p/4370084.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!