1.链表创建+遍历
1)
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct Node {
int data;
struct Node* pnext;
}*Pnode;
Pnode create_list();
void traverse_list(Pnode phaed);
int main(void) {
Pnode phead = NULL;
phead = create_list();
traverse_list(phead);
return 0;
}
Pnode create_list() {
int i;
int val;
int len;
Pnode phead = (Pnode)malloc(sizeof(Node));
if (phead == NULL) {
printf("分配失败!\n");
exit(-1);
}
Pnode ptail = phead;
printf("请输入要生成链表的节点个数:");
scanf("%d", &len);
for (i = 0; i < len; i++) {
printf("请输入要输入的第%d个节点的数值:", i + 1);
scanf("%d", &val);
Pnode pnew = (Pnode)malloc(sizeof(Node));
if (pnew == NULL) {
printf("分配失败!\n");
exit(-1);
}
pnew->data = val;
pnew->pnext = NULL;
ptail->pnext = pnew;
ptail = pnew;
}
return phead;
}
void traverse_list(Pnode phead) {
Pnode p = phead->pnext;
while (p != NULL) {
printf("%d ", p->data);
p = p->pnext;
}
printf("\n");
return;
}
2)
#include <stdio.h>
#include <stdlib.h>
#include<malloc.h>
typedef struct Node
{
int data;
struct Node *pnext;
}node,*Pnode;
Pnode create_list();
void traverse_list(Pnode phead);
int main()
{
Pnode phead=NULL;
phead=create_list();
traverse_list(phead);
return 0;
}
Pnode create_list()
{
int len;
int val;
int i;
Pnode phead=(Pnode)malloc(sizeof(node));
Pnode ptail=phead;
if(phead==NULL)
{
printf("false\n");
exit(-1);
}
printf("请输入你想生成的节点个数:");
scanf("%d",&len);
for(i=0; i<len; i++)
{
Pnode pnew=(Pnode)malloc(sizeof(node));
if(pnew==NULL)
{
printf("false\n");
exit(-1);
}
printf("请输入第%d个节点的数值:",i+1);
scanf("%d",&val);
pnew->pnext=NULL;
pnew->data=val;
ptail->pnext=pnew;
ptail=pnew;
}
return phead;
}
void traverse_list(Pnode phead){
Pnode p=phead->pnext;
while(p!=NULL){
printf("%d ",p->data);
p=p->pnext;
}
printf("\n");
return;
}