第十章-3-结构体练习

/*
 * @Issue: 已知head指向带头结点的单向链表,链表中每个结点抱哈字符型数据域(data)和指针域(next),编写程序
 *         实现在值为a的结点前插入值为key的结点,若没有值为a的结点,则插入在链表最后
 * @Author: 一届书生
 * @LastEditTime : 2020-02-11 09:51:30
 */
#include<iostream>
using namespace std;

typedef struct node{
    char data;
    struct node *next;
}linklist;

void insert(linklist *head,char a,char key){
    linklist *s;//插入结点
    s=new linklist[sizeof(node)];
    s->data=key;
    linklist *p,*q;
    q=head;p=head->next;
    if(p==NULL){
        s->next=NULL;
        q->next=s;
        return;
    }
    while((p->next!=NULL)&&(p->data!=a)){
        q=p;
        p=p->next;
    }
    if(p->data==a){
        s->next=p;
        q->next=s;
    }
    else{
        s->next=NULL;
        p->next=s;
    }
}

int main(){
    
    return 0;
}

  第二个题目是链表倒置,好久没写了,都忘了,附个图

/*
 * @Issue: head指向一个带有头结点的单向链表,链表中每个结点饱和字符型数据域(data)和指针域(next),实现倒置
 * @Author: 一届书生
 * @LastEditTime : 2020-02-11 10:42:05
 */
#include<iostream>
using namespace std;

typedef struct node{
    char data;
    struct node *next;
}linklist;

// 初始化
 linklist *craetlist(){
    linklist *p,*q,*ph;  //q:头结点 p:插入的结点 
    ph=new linklist[sizeof(node)];
    q=ph;
    char a;
    cin>>a;
    while(a!='z'){
        p=new linklist[sizeof(node)];
        p->data=a;
        q->next=p;
        q=p;
        cin>>a;
    }
    q->next=NULL;
    return (ph);
}

//倒置
void inversion(linklist *head){
    linklist *p,*q;
    p=head->next;
    head->next=NULL;
    while(p!=NULL){
        q=p->next;
        p->next=head->next;
        head->next=p;
        p=q;
    }
}

int main(){
    linklist *head;
    head=craetlist();
    linklist *p=head;
    cout<<"倒置前:"<<endl;
    while(p->next!=NULL){
        p=p->next;
        cout<<p->data<<" ";
    }
    inversion(head);
    cout<<endl<<"倒置后:"<<endl;
    linklist *q=head;
    while(q->next!=NULL){
        q=q->next;
        cout<<q->data<<" ";
    }
    
    return 0;
}

  

猜你喜欢

转载自www.cnblogs.com/52dxer/p/12294135.html