题目描述:请填写缺失代码完成程序,实现如下功能:首先根据键盘随机输入,以0结束的若干非零整数建立单链表;然后根据输入的两个索引位置交换链表上的两个结点(链表首元素索引为1,
#include <stdio.h>
#include <malloc.h>
struct cell {//单链表结点结构体定义
int x;
struct cell* next;
};
struct cell* build(void) {//新建单链表,并将建好的单链表首结点地址返回
struct cell* head, * tmp, * p;
head = tmp = p = NULL;
int n;
head = (cell*)malloc(sizeof(cell));
head->next = NULL;
tmp = head;
while (head != NULL) {
scanf("%d", &n);
if (n == 0)break;
p = (cell*)malloc(sizeof(cell));
p->x = n;
tmp->next = p;
p->next = NULL;
tmp = p;
}
if (head->next == NULL) {
free(head);
head = NULL;
}
return head;//返回单链表头
}
struct cell* swap(struct cell* head, int m, int n) {//交换索引为m和n的两个结点,head是单链表首结点指针
if (head == NULL) return NULL;
struct cell* pm = head, * pn = head;
struct cell* pm0 = NULL, * pn0 = NULL;
struct cell* tmp;
int i;
for (i = 1; i < m && pm != NULL; i++) {
pm0 = pm;
pm = pm->next;
}
for (i = 1; i < n && pn != NULL; i++) {
pn0 = pn;
pn = pn->next;
}
if (pm != NULL && pn != NULL && m != n) {//索引为m,n的结点位于链表中间
int temp;
if (pm0 != NULL && pn0 != NULL) {//中间
temp = pm->next->x;
pm->next->x = pn->next->x;
pn->next->x = temp;
}
if (pm0 == NULL && pn0 != NULL) { //pm0为头部 n>m
temp = head->next->x;
head->next->x = pn->next->x;
pn->next->x = temp;
}
if (pm0 != NULL && pn0 == NULL) { //pn0尾部 m>n
temp = head->next->x;
head->next->x = pm->next->x;
pm->next->x = temp;
}
}
return head;
}
void print(struct cell* head) {//打印整个单链表,head是单链表首结点指针
struct cell* tmp, * p;
tmp = head->next;
while (tmp != NULL) {
printf("%d", tmp->x);
if (tmp->next != NULL)printf(" ");
tmp = tmp->next;
}
}
void release(struct cell* head) {//释放单链表空间,head是单链表首结点指针
struct cell* temp, * p;
temp = head;
while (temp != NULL) {
p = temp;
temp = temp->next;
free(p);
}
}
int main(void) {
struct cell* head;
int m, n;
head = build();
scanf("%d %d", &m, &n);
head = swap(head, m, n);
if (head != NULL)
print(head);
else
printf("NULL");
release(head);
}