码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode(19) Remove Nth Node From End of List

时间:2015-08-08 18:23:31      阅读:89      评论: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,要求删除链表中倒数第n个结点,返回链表头结点。
题目不难,主要是必须考虑周全;

  • head==NULL || n==0,则直接返回head
  • 链表中结点总数count < n,则直接返回head
  • 链表中结点总数count == n,则head=head->next,返回head
  • 删除中间或尾结点,即删除正序第count-n+1 个结点,将倒序改为正序处理

AC代码

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        if (head == NULL || n == 0 )
            return head;

        //计算链表中的结点个数
        int count = 0;
        ListNode *p = head;
        while (p)
        {
            count++;
            p = p->next;
        }

        //链表中的结点个数小于要删除的倒数第n个
        if (count < n)
        {
            return head;
        }
        else if (count == n)
        {
            ListNode *tem = head;
            head = head->next;
            delete tem;
        }
        else{
            ListNode *p = head, *q = p->next;
            int i = 1;
            while (i < (count - n) && q->next!=NULL)
            {
                p = p->next;
                q = q->next;
                i++;
            }
            p->next = q->next;
            delete q;
        }
        return head;

    }
};

GitHub测试程序源码

LeetCode(19) Remove Nth Node From End of List

标签:

原文地址:http://blog.csdn.net/fly_yr/article/details/47359743

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!