2.2.7—单链表—Remove Nth Node From End of List

来源:互联网 发布:淘宝游戏专营怎么进入 编辑:程序博客网 时间:2024/06/08 18:47
描述
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.
Aer 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.

#include<iostream>using namespace std;struct node{int data;node *next;};class mylist{node *head;public:mylist(){head = new node();head->next = NULL;}void CreateList(int a[], int n);void Display();friend void RemoveNthNodeFromEnd(mylist &list, int n);~mylist();};void mylist::CreateList(int a[], int n){node *p = head;for (int i = 0; i < n; i++){node *q = new node();q->data = a[i];p->next = q;p = q;}p->next = NULL;}void mylist::Display(){node *p = head->next;while (p){cout << p->data << " ";p = p->next;}cout << endl;}void RemoveNthNodeFromEnd(mylist &list, int n){node *p1 = list.head->next;node *p2 = list.head->next;node *pre = list.head;//===for (int i = 1; i < n; i++)p2 = p2->next;while (p2->next!=NULL){p2 = p2->next;p1 = p1->next;pre = pre->next;}pre->next = p1->next;delete p1;}mylist::~mylist(){node *p = head;while (head){head = p->next;delete p;p = head;}}int main(){//===const int n = 5;int a[n] = { 1, 2, 3, 4, 5 };mylist list;list.CreateList(a, n);list.Display();//===int k= 1;RemoveNthNodeFromEnd(list,k);list.Display();}