链表

来源:互联网 发布:720全景软件 编辑:程序博客网 时间:2024/05/01 06:09

编写一个程序,要求:从终端输入一组整数,以0作为结束标志,将这一组整数存放在一个链表中(结束标志0不包括在内),打印出该链表中的值,然后删除该链表中的第五个元素,打印出删除后的结果。最后在内存中释放掉该链表。



#include"stdio.h"
//#include"conio.h"
#include<malloc.h>
#include<iostream>

using namespace std;

typedef int elemptype;

typedef struct node {
    elemptype data;
    struct node* next;
};

node* creatlist(int n)
{
    node *list = NULL;
    node *p1, *p2;
    int i;
    elemptype e;
    p1 = (node*)malloc(sizeof(node));            //在循环输入数据的循环之外
    for (i = 1; i <= n; i++)
    {
        cout << "put first number" << endl;
        cin >> e;
        p2 = (node*)malloc(sizeof(node));       //两处的申请内存不能放一块,加在最后的能必须得在循环内申请
        p2->data = e;
        p2->next = NULL;
        if (!list)
        {
            list=p1= p2;
        
        }
        else
            p1->next = p2;
        p1 = p2;
    }
    return list;
}

void prin(node*list)
{
    //if (list == NULL)
    //    cout << "链表为空" << endl;
    node*p;
    p = list;
    while (p)
    {
        cout << p->data << endl;
        p = p->next;
    }
    return;
}

void insertList(node* list, node* q, elemptype e)
{
    node* p;
    p = (node*)malloc(sizeof(node));
    p->data = e;
    if (!list)
    {
        list = p;
        p->next = NULL;
    }
    else
    {
        p->next = q->next;
        q->next = p;
    }
}

void delLink(node*list, node*q)
{
    node* r;
    if (list == q)
    {
        list->next = q->next;
        free(q);
    }
    else
    {
        for (r = list; r->next != q; r = r->next);
    
            if (r->next != NULL)
            {
                r->next = q->next;
                free(q);
            }
        }

}

//node* destroylist(node* list)
void destroylist(node* list)
{
    node* p, *q;
    p = list;
    while (p)
    {
        q = p->next;
        free(p);
        p = q;
    }
    list = NULL;
    //return list;
}


void main()
{
    node*q, *l;
    l=q = creatlist(1);
    int e, i;
    cin >> e;
    while (e)
    {
        insertList(l, q, e);
        q = q->next;
        cin >> e;
    }
    q = l;
    prin(l);
    for (i = 0; i < 4; i++)                //用循环的方式找到的5个要删除的元素。
    {
        q = q->next;
    }

    delLink(l, q);
    prin(l);
    destroylist(l);
    //l=destroylist(l);
    //prin(l);
}
0 0
原创粉丝点击