#include<stdio.h> #include<stdlib.h> typedef struct Node { int data; struct Node next; }Node; void push(Node**p,int data1) { Node * h1= * p; Node * newNode=(Node)malloc(sizeof(Node)); newNode->data =data1; newNode->next =NULL; if(h1==NULL) { h1=newNode; return; } else{ for(h1=p;h1->next!=NULL;h1=h1->next) { ; } h1->next=newNode; } } void push2(Node**p,int data1) { Node * h1= * p; Node * newNode=(Node)malloc(sizeof(Node)); newNode->data =data1; newNode->next =NULL; if(h1==NULL) { h1=newNode; return; } else{ for(h1=p;h1->next!=NULL;h1=h1->next) { ; } h1->next=newNode; } } Node * merge(Nodeh1,Nodeh2) { Node * p; Node l1=h1; Node * l2=h2; p=(Node*)malloc(sizeof(Node)); while(h1!=NULL&&h2!=NULL) { if(h1->data>=h2->data) { p->next=h2; h2=h2->next; } else{ p->next=h1; h1=h1->next; } p=p->next; } if(h1==NULL) { p->next=h2; } else p->next=h1; return p; } void print(Node * p) { for(;p!=NULL;p=p->next) printf("%d",p->data); } int main(void) { Node * h1; Node* h2; push(&h1,10); push(&h1,10); push2(&h2,20); push2(&h2,30); print(h1); return 0; }代码有错误吗
时间: 2024-03-25 10:38:39 浏览: 24
代码中存在一些错误:
1. 在定义结构体时,节点指针 next 应该是一个指向结构体的指针,而不是结构体本身。应该改为:
```
typedef struct Node {
int data;
struct Node *next;
} Node;
```
2. 在 push 函数中,应该使用指针的指针来修改指针变量的值。应该改为:
```
void push(Node **p, int data1) {
Node *h1 = *p;
Node *newNode = (Node *)malloc(sizeof(Node));
newNode->data = data1;
newNode->next = NULL;
if (h1 == NULL) {
*p = newNode;
return;
} else {
for (h1 = *p; h1->next != NULL; h1 = h1->next) {
;
}
h1->next = newNode;
}
}
```
3. 在 merge 函数中,定义变量 l1 和 l2 后没有使用。应该改为:
```
Node *merge(Node *h1, Node *h2) {
Node *p;
p = (Node *)malloc(sizeof(Node));
Node *tail = p;
while (h1 != NULL && h2 != NULL) {
if (h1->data >= h2->data) {
tail->next = h2;
h2 = h2->next;
} else {
tail->next = h1;
h1 = h1->next;
}
tail = tail->next;
}
if (h1 == NULL) {
tail->next = h2;
} else {
tail->next = h1;
}
return p->next;
}
```
4. 在 print 函数中,应该输出每个节点的 data 值后再换行。应该改为:
```
void print(Node *p) {
for (; p != NULL; p = p->next) {
printf("%d ", p->data);
}
printf("\n");
}
```
除此之外,在 main 函数中,应该将 h1 和 h2 初始化为 NULL,才能正确地使用 push 函数。应该改为:
```
int main(void) {
Node *h1 = NULL;
Node *h2 = NULL;
push(&h1, 10);
push(&h1, 20);
push2(&h2, 30);
push2(&h2, 40);
Node *merged = merge(h1, h2);
print(merged);
return 0;
}
```
这样,代码才能正确运行。