首页 > 代码库 > 【LeetCode】Remove Nth Node From End of List (2 solutions)
【LeetCode】Remove Nth Node From End of List (2 solutions)
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.
这题的难点在于one pass
没到尾部就没法进行倒退n个节点的操作。
但是到达尾部之后,再进行倒退删除操作,就不满足one pass了
由此诞生解法一:使用数组记录所有节点的位置,通过下标计算(尾节点位置-n+1)立刻定位到需要删除的节点了
建立vector存放ListNode*,每个指针指向一个链表节点
/** * 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) { vector<ListNode*> v; ListNode* cur = head; while(cur != NULL) { ListNode* p = cur; v.push_back(p); cur = cur->next; } int size = v.size(); int num = size-n; if(num == 0)//first, no pre return head->next; else if(num == size-1)//last but not first, no post { v[num-1]->next = NULL; return head; } else //pre link to post { v[num-1]->next = v[num+1]; return head; } }};
仔细分析之后觉得浪费空间太多。
我们只是通过尾节点位置确定需要删除节点(n-1个偏移量),不需要其他的位置信息。
只需要两个位置相差n-1的指针,当前面的指针指向尾节点时,后面的节点即指向需要删除的节点。
由此产生解法二:
/** * 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; //the node at the last node ListNode* preslow = NULL; ListNode* slow = head; //the node to delete int i = 1; while(i < n) { fast = fast->next; i ++; } while(fast->next != NULL) { fast = fast->next; preslow = slow; slow = slow->next; } //fast at the last node, slow at the node to delete if(preslow == NULL) //delete the head return head->next; else { preslow->next = slow->next; return head; } }};
【LeetCode】Remove Nth Node From End of List (2 solutions)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。