程序填空题:单链表的最大结点移动表尾
本题要求将链表中最大的结点移动到表尾,要求采用冒泡算法进行比较和移动。
```c
#include
#include
typedef int DataType;
struct Node {
DataType data;
struct Node* next;
};
typedef struct Node *PNode;
typedef struct Node *LinkList;
LinkList SetNullList_Link()
{
LinkList head = (LinkList)malloc(sizeof(struct Node));
if (head != NULL) head->next = NULL;
else printf("alloc failure");
return head;
}
void CreateList_Head(struct Node *head)
{
PNode p = NULL; int data;
scanf_s("%d", &data);
while (data != -1) {
p = (struct Node*)malloc(sizeof(struct Node));
p->data = data;
p->next = head->next;
head->next = p;
scanf("%d", &data);
}
}
void MoveMaxToTail(LinkList head)
{
PNode p, q;
DataType temp;
p = head->next;
q = p->next;
while (q != NULL)
{
if ( @@[p->data > q->data](2) )
{
temp = q->data;
q->data = p->data;
p->data = temp;
}
else
{
@@[ p = q;
q = q->next;](4)
}
}
}
void print(LinkList head)
{
PNode p = head->next;
while (p)
{
printf("%d ", p->data);
p = p->next;
}
}
void DestoryList_Link(LinkList head)
{
PNode pre = head;
PNode p = pre->next;
while (p)
{
free(pre);
pre = p;
p = pre->next;
}
free(pre);
}
int main()
{
LinkList head = NULL;
head = SetNullList_Link();
CreateList_Head(head);
MoveMaxToTail(head);
print(head);
DestoryList_Link(head);
return 0;
}
```
答案:
第1空:p->data > q->data
第2空: p = q;
q = q->next;
```c
#include
#include
typedef int DataType;
struct Node {
DataType data;
struct Node* next;
};
typedef struct Node *PNode;
typedef struct Node *LinkList;
LinkList SetNullList_Link()
{
LinkList head = (LinkList)malloc(sizeof(struct Node));
if (head != NULL) head->next = NULL;
else printf("alloc failure");
return head;
}
void CreateList_Head(struct Node *head)
{
PNode p = NULL; int data;
scanf_s("%d", &data);
while (data != -1) {
p = (struct Node*)malloc(sizeof(struct Node));
p->data = data;
p->next = head->next;
head->next = p;
scanf("%d", &data);
}
}
void MoveMaxToTail(LinkList head)
{
PNode p, q;
DataType temp;
p = head->next;
q = p->next;
while (q != NULL)
{
if ( @@[p->data > q->data](2) )
{
temp = q->data;
q->data = p->data;
p->data = temp;
}
else
{
@@[ p = q;
q = q->next;](4)
}
}
}
void print(LinkList head)
{
PNode p = head->next;
while (p)
{
printf("%d ", p->data);
p = p->next;
}
}
void DestoryList_Link(LinkList head)
{
PNode pre = head;
PNode p = pre->next;
while (p)
{
free(pre);
pre = p;
p = pre->next;
}
free(pre);
}
int main()
{
LinkList head = NULL;
head = SetNullList_Link();
CreateList_Head(head);
MoveMaxToTail(head);
print(head);
DestoryList_Link(head);
return 0;
}
```
答案:
第1空:p->data > q->data
第2空: p = q;
q = q->next;