C链表

#include <stdio.h>
#include <stdlib.h>
 
struct grade {
  int score;
  struct grade *next;
};
typedef struct grade NODE;  //typedef为C语言的关键字,作用是为一种数据类型定义一个新名字。
//使用typedef目的一般有两个,一个是给变量一个易记且意义明确的新名字,
//另一个是简化一些比较复杂的类型声明。
struct grade *create();   //创建链表
void insert(NODE *head,NODE *pnew,int i);   //插入链表
void pdelete(NODE *head,int i);   //删除列表
void display(NODE *head);   //输出链表
void Pfree(NODE *head);    //销毁链表
 
int main(int argc, char *argv[]) {
    struct grade *head,*pnew;
    head=create();
    if (head==NULL)
        return 0;
    printf("输出创建的链表:");
    display(head);
    pnew=(NODE *)malloc(sizeof(NODE));
    if (pnew==NULL) {
        printf("创建失败!");
        return 0;
    }
    pnew->score=88;
    insert(head,pnew, 3);   //将新节点插入节点3的后面
    printf("插入后的链表:");
    display(head);
    pdelete(head,3);   //删除节点3
    printf("删除后的链表:");
    display(head);
    Pfree(head);
    return 0;
}
 
struct grade *create() {
    NODE *head,*tail,*pnew;
    int score;
    head=(NODE *)malloc(sizeof(NODE));  //创建头节点。
    if (head==NULL) { //创建失败返回
        printf("创建失败!");
        return NULL;
    }
    head->next=NULL;  //头节点指针域置NULL
    tail=head;  // 开始时尾指针指向头节点
    printf("输入学生成绩:");
    while (1) { //创建链表
        scanf("%d",&score);
        if (score<0) //成绩为负是退出循环
            break;
        pnew=(NODE *)malloc(sizeof(NODE));  //创建新节点
        if (pnew==NULL) { //创建失败返回
            printf("创建失败!");
            return NULL;
        }
        pnew->score=score;  //新节点数据域存放输入的成绩
        pnew->next=NULL;   //新节点指针域置NULL
        tail->next=pnew;  //新节点插入到表尾
        tail=pnew;   //为指针指向当前的尾节点
    }
    return head;  //返回创建链表的头指针
}
void display(NODE *head) {
    NODE *p;
    for (p=head->next; p!=NULL; p=p->next)
        printf("%d ",p->score);
    printf("
");
}

参考:https://www.oschina.net/code/snippet_105637_43706

1. typedef struct
(1) 

struct{ int x; int y; }test1; 
定义了 结构 test1, test1.x 和 test1.y 可以在语句里用了。

(2) 

struct test {int x; int y; }test1; 

定义了 结构 test1,
test1.x 和 test1.y 可以在语句里用了。
与 1 比,省写 了 test

(3)

typedef struct test{
    int x; int y;
}text1,text2; 

这种结构 的(类型)别名 叫 text1 或叫 text2

(4)

typedef struct LNode{
    char data;
    struct LNode *next;
}LNode,*LinkList;

LNode为struct LNode{}创建了一个别名,以后用LNode来代替struct LNode,
LinkList是创建LinkList类型的指针,代替所有指向这个结构的指针(LinkList代替struct LNode *)。

(5)举例

#include<stdlib.h>
#include<stdio.h>
int main(){
    typedef struct test{
        int a;
        int b;
    }tt;
    struct test t;
    tt testt;   //tt = struct test
    t.a=1;
    testt.b=2;
    printf("a:%d
",t.a);
    printf("b:%d
",testt.b);
    return 0;
}
原文地址:https://www.cnblogs.com/stellar/p/8630235.html