链表的创造(我的困难主要在这)

来源:互联网 发布:新版mac mini 发布时间 编辑:程序博客网 时间:2024/05/17 04:58

           在这两天的学习中主要是对链表的创造这块有些费解,而网上的大多数代码都是一笔带过,真是看了还不如不看。最终博主看了网上一位大牛的博客然后顿悟了。

主要是在指针那块。

#include <iostream>
#include <cstdio>
#include <cstdlib>
#define ERROR 0

using namespace std;
typedef struct student{
    int num;
    float score;
    struct student *next;
}node,*Linklist;
int n;//节点总数
/*创建链表*/
Linklist create(){
    Linklist head;
    Linklist p1;
    Linklist p2;

    n = 0;
    p1=(Linklist )malloc(sizeof(node));
    p2=p1;//将p1赋予p2;

    if(p1 == NULL){
        return NULL;
    }
    else{
        head=NULL;
        cin>>p1->num>>p1->score;
    }

    while(p1->num!=0){
        n+=1;
        if(n==1){
            head = p1;//头指针为head
            p2->next = NULL;//之前已经将p1赋予p2,所以可以理解为p1->next
        }
        else{
            p2->next = p1;//此处是p2的next指针指向p1
        }

        p2 = p1;/*将p1赋予p2,下面会重新分配内存,因为p2的next会指向p1。相当于
上一个p1的next指向了下一个p1*/
        p1 = (Linklist)malloc(sizeof(node));
        cin>>p1->num>>p1->score;
    }
    p2->next = NULL;
    free(p1);
    p1 = NULL;
    return head;
}
void printfstudent(Linklist head){
    Linklist p;
    p=head;
    if(head!=NULL){
        while(p!=NULL){
            cout<<p->num<<"   "<<p->score<<endl;
            p=p->next;
        }
    }
}
int main()
{
    Linklist head;
    head = create();
    printfstudent(head);
    return 0;
}


0 0