链表初识之功能不完善的链表

来源:互联网 发布:sql anywhere 12 下载 编辑:程序博客网 时间:2024/05/17 20:30

第一种解决方法永远要是自己想来的,即使是错的,不然就无法学习别人的。-----2014--04--28

#define _CRT_SECURE_NO_WARNINGS#include<stdio.h>#include<stdlib.h>typedef struct Node{    int data;    struct Node *next;}SLIST;//创建 增加 删除  移动    输出//删除xSLIST* del_Slist(SLIST *pHead, int x){    SLIST *p1 = pHead, *p = NULL, *p2 = p1->next;    while (1)    {        if (p2->data == x)        {            p1->next = p2->next;            free(p2);            break;        }        p1 = p2;        p2 = p1->next;    }    return pHead;}//在结点数值为x的前面插入ySLIST* add_Slist(SLIST *pHead, int x, int y){    SLIST *p1 = pHead, *p = NULL, *p2 = p1->next;    while (1)    {        if (p2->data==x)        {            p = (SLIST *)malloc(sizeof(SLIST));            p->data = y;            p1->next = p;                 //    在此处犯错 写成 p = p1->next            p->next = p2;                 //    在此处犯错 同上            break;        }        p1 = p2;        p2 = p1->next;    }    return pHead;}SLIST *Creat_Slist(){    //1 创建头结点并初始化    int data = 0;    SLIST *pHead = NULL, *pM = NULL, *pCur;    pHead = (SLIST *)malloc(sizeof(SLIST));    pHead->data = 0;    pHead->next = NULL;    //2 循环创建结点, 结点数据域中的数值从键盘输入,    //以-1作为输入结束标志    printf("Please enter the data of node(-1:quit) ");    scanf("%d", &data);    //准备环境 让pCur指向pHead    pCur = pHead;    while (data != -1)    {        //不断的malloc新结点 并且数据域 赋值        pM = (SLIST *)malloc(sizeof(SLIST));        pM->data = data;        pM->next = NULL;        //1新节点入链表        pCur->next = pM;        //2当前节点下移        pCur = pM;        printf("Please enter the data of node(-1:quit) ");        scanf("%d", &data);    }    return pHead;}int Slist_print(SLIST *pHead){    SLIST *p = NULL;    if (pHead==NULL)    {        return -1;    }    //准备环境    p = pHead->next;    printf("\nBegin ");    while (p)    {        printf("%d ", p->data);        p = p->next;    }    printf("End");    return 0;}void main(){    SLIST *pHead = NULL;    pHead = Creat_Slist();    Slist_print(pHead);    pHead=add_Slist(pHead, 30, 100);    Slist_print(pHead);    del_Slist(pHead, 100);    Slist_print(pHead);    system("pause");}

0 0