首页 > 代码库 > 链表相关

链表相关

#include "stdafx.h"#include<iostream>using namespace std;struct linklist {    struct linklist* next;    int data;};void remove(linklist *head);//去除重复项linklist *findnthlast(linklist *head,int n);//找到倒数第n个元素int main(){    int input;    linklist *p,*n,*head;    head=new linklist;    cin>>head->data;    head->next=NULL;    p=head;    while (cin>>input)    {        n=new linklist;        n->data=http://www.mamicode.com/input;        n->next=NULL;        p->next=n;        p=n;    }    remove(head);    cout<<findnthlast(head,3)->data<<endl;    p=head;    while(p)    {        cout<<p->data<< ;        p=p->next;    }}void remove(linklist *head){    linklist *p=head,*q,*s;    while (p!=NULL)                      //!!    {        q=p->next;        s=p;        int data=http://www.mamicode.com/p->data;        while(q!=NULL)        {            if(q->data=http://www.mamicode.com/=data)             {                s->next=q->next;                    delete q;                         //!!                q=s->next;                            }            else {s=q;q=q->next;}        }        p=p->next;    }}linklist *findnthlast(linklist *head,int n){    if(head==NULL) return NULL;    linklist*p=head,*q=head;    int cnt=n;                            //!!    while(q!=NULL)                   //!!    {if (cnt>0)        {            q=q->next;            --cnt;        }        else        {            p=p->next;            q=q->next;        }    }    if(cnt==0) return p;    else return NULL;}

 

链表相关