LeetCode 算法习题 第四周

来源:互联网 发布:美容院微管理软件 编辑:程序博客网 时间:2024/06/05 18:59

19. 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.

题目大意:

删去倒数第n个节点

我的解答:

/** * 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) {        ListNode* fast = head;        ListNode* slow = head;       if(n==0)return head;//此时不删除节点,直接返回head        for(int i = 0; i < n; i++) fast = fast -> next;//将fast和slow拉开长为n的距离        if(fast == NULL) return head->next;//如果时删除第一个节点,就直接返回head->next,否则在下面的循环 head -> next 就会报错了        while(fast->next != NULL){            fast = fast->next;            slow = slow->next;        }//将fast移动到最后,同时移动slow        if(slow != NULL)        slow -> next = slow ->next ->next;//删去中间节点,可以不判断slow,因为先前已经讨论过n=0的情况了        return head;    }};
原创粉丝点击