链表遍历一次删除倒数第N个节点

来源:互联网 发布:ubuntu解压gz文件 编辑:程序博客网 时间:2024/06/15 06:47
刷 leetcode的 Remove Nth Node From End of List 的题目,一开始想这算是easy的题目了,只需要遍历一次,记录n个节点,然后减去倒数的节点数,就得到所要删除的节点。但是没注意题目的只遍历一次。
解决这道题目的主要思路是,设立两个指针,快指针和慢指针,这两个指针同时指向初始位置。快指针先移动N个节点,快节点和慢节点同时移动,当快节点移动到末尾时,慢节点处于要删除节点的next节点。
代码写得比较烂,后期在改进。
#include<iostream>#include<vector>#include<string> using namespace std;typedef struct ListNode {int val;ListNode *next;}ListNode;class Solution {public:ListNode* removeNthFromEnd(ListNode* head, int n) {ListNode *cur = head;ListNode *index=head;ListNode *temp;for (int i = 0; i < n; i++){cur = cur->next;}if (cur == NULL){head =head->next;return head;}while (cur->next != NULL){index = index->next;cur = cur->next;}index->next= index->next->next;return head;}};void CreatList(ListNode* & head,int *a){for (int i = 0; i < 5; i++){ListNode *temp=new ListNode;temp->val = a[i];        head->next=temp;head = head->next;}head->next = NULL;}int main(){Solution s;int n;cin >> n;int arr[5] = {1,2,3,4,5};ListNode *head=new ListNode;ListNode *OutPut = head;CreatList(head,arr);OutPut=s.removeNthFromEnd(OutPut->next, n);while (OutPut != NULL){cout << OutPut->val << endl;OutPut = OutPut->next;}system("pause");}

原创粉丝点击