p -> next = head -> next;
head -> next = p;
上面为网上大多数的头插法建立单链表;
p->next=head;
head=p;
这是我写的头插法创建单链表,运行出来是没有错误的,不知道这样写对不对,有没有容易忽略的地方
你写的头插法创建单链表是正确的,两种写法本质上是等价的。只是第一种写法在插入第一个节点时需要特殊处理,而第二种写法则不需要。
头插法,尾插法:核心就是初始化操作,指定结点的后插操作
你写的头插法创建单链表也是可以的。两种方法本质上是一样的,只是操作的顺序不同。你的代码没有问题,可以正常运行。以下是一个简单的例子:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node* createList(int n) {
Node *head = NULL;
for (int i = 0; i < n; i++) {
Node *p = (Node*)malloc(sizeof(Node));
printf("请输入第%d个节点的值:", i + 1);
scanf("%d", &(p->data));
p->next = head;
head = p;
}
return head;
}
void printList(Node *head) {
Node *p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
int n;
printf("请输入链表的长度:");
scanf("%d", &n);
Node *head = createList(n);
printf("创建的链表为:");
printList(head);
return 0;
}