leetcode_019Remove Nth Node From End of List

来源:互联网 发布:阿里云电子发票 编辑:程序博客网 时间:2024/06/05 12:46

移除单链表倒数第N个节点。

测试平台是没有头结点的单链表!!!我最开始写的是带头结点的,所以测试不通过。

    ListNode* removeNthFromEnd(ListNode* head, int n) {        ListNode* temp = head;int i = 0;while (temp != NULL){++i;temp = temp->next;}if (i != n){temp = head;int time = i - n - 1;int j = 0;while (j != time){temp = temp->next;++j;}if (temp != NULL)temp->next = temp->next->next;return head;}else return head->next;    }


我个人觉得没有头结点的单链表各种操作都不怎么方便。我们在做插入、删除时可以为它创建一个头结点,最后再返回头结点的next就可以了。




0 0
原创粉丝点击