实现了简单的链表构造,完成了简单的插入(实际上还没有运行)、复制、输入输出
#include<stdio.h>
typedef struct Node{
//类型定义typedef,便于使用名称
int val;
struct Node *next;
//申请一块Node类型的地址,储存下一个Node
}Node;//此处的Node为使用声明
Node *CreateNode(int val){
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->val= val;
newNode->next = NULL;
return newNode;
}//通过一块地址来存储struct
Node *CreateNodeList(int *val,int n){
Node *headNode = CreateNode(val[0]);
//指针headnode指向新开辟的地址
//笔者一直以为指针是跟最初的指向对象绑定
Node *nowNode = headNode;
//跟数组类似,调用数组时需要知道a[0],
//于是此处用nowNode以保留headNode的指向
for(int i=1;i<n;i++){
nowNode->next=CreateNode(val[i]);
nowNode=nowNode->next;//nownode指针指向下一块Node类型地址
}
return headNode;
}
void InsertNode(int pos,Node *list,Node *Node){
while(--pos){
list=list->next;
}
Node->next=list->next;
Node=list->next;
}
void Print(Node *list){
//这里实质上传入的是头结点的地址
while(list!=NULL){
printf("%d ",list->val);
list=list->next;
}
printf("\n");
}
Node *CopyNode(Node *list1,int n){
Node *headNode = CreateNode(list1->val);
Node *list1now=list1;
Node *nowNode = headNode;
for(int i=1;i<n;i++){
list1now=list1now->next;
nowNode->next=CreateNode(list1now->val);
nowNode=nowNode->next;
}
return headNode;
}
int main()
{
int val[100],n;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d",&val[i]);
}
Node *list=CreateNodeList(val,n);
Node *list1=CopyNode(list,n);
Print(list);
Print(list1);
return 0;
}

被折叠的 条评论
为什么被折叠?



