C语言定义一个头节点,一个关于C语言链表头结点的问题

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼

#include

#include

#include

typedef struct STU{

int sno;

char sname[10];

float grade;

struct STU *next;

}STU;

STU *inputData(); /*创建链表,返回链表的头指针*/

void printData( STU *list); /*输出链表*/

int main()

{

STU *h=NULL;

h=inputData();

printData(h);

return 0;

}

STU *inputData()

{

STU *p=NULL,*q=NULL,*head=NULL;

int sno;

char sname[10];

float grade;

scanf("%d%s%f",&sno,sname,&grade);

while(sno!=-1) /*输入学号为-1时,结束输入*/

{

p=(STU *)malloc(sizeof(STU));

p->sno=sno;

strcpy(p->sname,sname);

p->grade=grade;

p->next=NULL;

if(head==NULL)

head=p;

else

q->next=p;

q=p;

scanf("%d%s%f",&sno,sname,&grade);

}

return head;

}

void printData( STU *list)

{

STU *p=list;

printf("\n======================\n");

while(p!=NULL)

{

___________________________________________; /*输出数据*/

p=p->next;

}

}

在C语言中,我们可以使用结构体和指针来创建一个双向表。首先,我们需要定义一个双向节点的结构: ```c typedef struct Node { int data; // 节点数据 struct Node* prev; // 指向前一个节点的指针 struct Node* next; // 指向下一个节点的指针 } Node; ``` 然后,我们创建一个头节点`h`: ```c Node* h = (Node*)malloc(sizeof(Node)); // 分配内存 h->data = 0; // 初始化头节点的数据 h->prev = NULL; // 头节点前驱为空 h->next = NULL; // 头节点后继也为空 ``` 接下来,我们添加插入操作。假设我们要在指定位置`pos`插入一个新的节点`new_node`,数据为`value`: ```c // 插入函数 void insert(Node** head, int pos, int value) { Node* newNode = (Node*)malloc(sizeof(Node)); newNode->data = value; newNode->prev = NULL; newNode->next = *head; if (pos == 0) { // 插入到最前面 newNode->next->prev = newNode; *head = newNode; } else { Node* current = *head; for (int i = 1; i < pos && current != NULL; ++i) { current = current->next; } if (current != NULL) { // 找到了插入位置 newNode->prev = current->prev; newNode->next = current; current->prev->next = newNode; current->prev = newNode; } } } ``` 最后,记得在不需要表的时候释放节点内存: ```c void freeList(Node* node) { while (node != NULL) { Node* temp = node; node = node->next; free(temp); } } // 使用时,在适当的位置调用insert函数,并在完成时可能需要freeList(h) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值