好啦,旧题重写
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int val;
struct Node* next;
} Node, *List;
List add(List head, int num) {
List p = (List)malloc(sizeof(Node));
p->val = num;
p->next = NULL;
head->next = p;
return p;
}
List Create() {
int n;
scanf("%d", &n);
List dummy = (List)malloc(sizeof(Node));
dummy->val = -1;
dummy->next = NULL;
List head = dummy;
while(n--) {
int num;
scanf("%d", &num);
head = add(head, num);
}
return dummy;
}
List Insert(List dummy, int num) {
List head = dummy->next;
List p = (List)malloc(sizeof(Node));
p->val = num;
p->next = NULL;
if(head == NULL || num < head->val) {
p->next = head;
dummy->next = p;
return dummy;
}
while(head->next) {
if(num < head->next->val && num > head->val) {
p->next = head->next;
head->next = p;
return dummy;
}
head = head->next;
}
if(num > head->val) head->next = p;
return dummy;
}
void Print(List head) {
while(head->next) {
printf("%d ", head->val);
head = head->next;
}
printf("%d", head->val);
}
int main() {
List dummy = Create();
int num;
scanf("%d", &num);
dummy = Insert(dummy, num);
Print(dummy->next);
return 0;
}
测试点2 主要是段错误 是因为我们默认忽视了链表长度为0的特殊情况
其他还需要注意的就是 插入的时候分为 头插 尾插 中间插入(这两个if语句的顺序不要搞反,否则会发生段错误,原因很简单,仔细想想就能明白,或者你留言) 至少我没有想到合三为一的方法,我分类讨论了一下(有冲浪的大神看到我的代码,可以指点一下)
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int val;
struct Node* next;
} Node, *List;
Node* create(List head, int num) {
Node* p = (Node*)malloc(sizeof(Node));
p->val = num;
p->next = NULL;
head->next = p;
return p;
}
int search(List head, int num) {
int ok = 0;
for(Node* p = head; p; p = p->next) {
if(p->val == num) {
ok = 1;
break;
}
}
return ok;
}
void insert(List dummy, int num) {
Node* head = dummy->next;
Node* newP = (Node*)malloc(sizeof(Node));
newP->val = num;
newP->next = NULL;
if(head == NULL) {
dummy->next = newP;
return;
}
if(num < head->val) {
newP->next = head;
dummy->next = newP;
return;
}
for(Node* p = head; p; p = p->next) {
if(num > p->val && p->next == NULL) {
p->next = newP;
break;
}else if(num > p->val && num < p->next->val) {
newP->next = p->next;
p->next = newP;
break;
}
}
}
void print(List head) {
for(Node* p = head; p; p = p->next) {
if(p->next == NULL) {
printf("%d", p->val);
break;
}
printf("%d ", p->val);
}
}
int main() {
int n;
scanf("%d", &n);
Node* dummy = (Node*)malloc(sizeof(Node));
dummy->next = NULL;
Node* head = dummy;
while(n--) {
int num;
scanf("%d", &num);
head = create(head, num);
}
int newNum;
scanf("%d", &newNum);
if(dummy->next == NULL || !search(dummy->next, newNum)) insert(dummy, newNum);
print(dummy->next);
return 0;
}