码迷,mamicode.com
首页 > 其他好文 > 详细

链表相关

时间:2014-09-04 11:42:30      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   div   sp   log   c   

#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=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=p->data;
        while(q!=NULL)
        {
            if(q->data==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;
}

 

链表相关

标签:style   blog   color   os   io   div   sp   log   c   

原文地址:http://www.cnblogs.com/just-tao/p/3954137.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!