单链表(带头结点)的创建与倒置

根据这篇博客而来:http://blog.csdn.net/zzzzhdx/article/details/79508736

代码如下:

//  
// Created by HP on 2018/3/9.  
//  
#include <iostream>
using namespace std;
struct node{
    int num;
    node *next;
};
int c;
int find(node *head,int key)
{
    node *finder=head->next;
    while(finder!=NULL){
        if(finder->num==key)//如果想要插入的数据已经在链表中  
            return  1;
        finder=finder->next;
    }
    return 0;
}
void CreateList(node *head)
{
    node *tail=head;
    int data;
    int n,i;
    cin>>n;
    for(i=0;i<n;i++){
        cin>>data;
        if(find(head,data)==0){
            node *s=new node;//创建新的节点  
            s->num=data;
            s->next=NULL;
            tail->next=s;//将新结点插入链表中  
            tail=s;
            c++;
        }
    }
}
void ShowList(node *head)
{
    int temp=c;
    cout<<c<<" ";
    node *display=head->next;
    while(display){
        c--;
        cout<<display->num<<" ";
        display=display->next;
    }
    c=temp;
    cout<<endl;
}
void Reverse(node *head)//链表倒置
{
    node *p,*q,*pr;
    p=head->next;
    q=NULL;
    head->next=NULL;
    while(p){
        pr=p->next;
        p->next=q;
        q=p;
        p=pr;
    }
    head->next=q;
}
int main()
{
    int t;
    cin>>t;
    while(t--){
        c=0;
        node *head=new node;
        head->next=NULL;
        CreateList(head);//创建  
        ShowList(head);//输出
        Reverse(head);//链表倒置
        ShowList(head);//输出
    }
    return 0;
}  

猜你喜欢

转载自blog.csdn.net/zzzzhdx/article/details/79563300
今日推荐