|
5鱼币
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int value;
struct Node *next;
};
void insertNode(struct Node **head, int value)
{
struct Node *pre;
struct Node *cur;
struct Node *new;
cur = *head;
pre = NULL;
while (cur != NULL && cur->value < value)
{
pre = cur;
cur = cur->next;
}
new = (struct Node *)malloc(sizeof(struct Node));
if (new == NULL)
{
printf("内存分配失败!\n");
exit(1);
}
new->value = value;
new->next = cur;
if (pre == NULL)
{
*head = new;
}
else
{
pre->next = new;
}
}
void printNode(struct Node *head)
{
struct Node *cur;
cur = head;
while (cur != NULL)
{
printf("%d ", cur->value);
cur = cur->next;
}
putchar('\n');
}
struct Node *reversed(struct Node *head)
{
struct Node *pre;
struct Node *cur;
pre = NULL;
cur = head;
while(cur)
{
struct Node *next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
int main(void)
{
struct Node *head = NULL;
int input;
printf("\n开始录入数据到单链表a...\n");
while (1)
{
printf("请输入一个整数(输入-1表示结束):");
scanf("%d", &input);
if (input == -1)
{
break;
}
insertNode(&head, input);
printNode(head);
}
printf("\n下面将单链表a原地反转...\n");
head = reversed(head);
printNode(head);
return 0;
}
reversed函数里的 "while(cur)" 这段步骤是怎么样的?最好详细点 |
|