5.链表的逆置:
已知head指向一个带头节点的单向链表,链表中每个结点包含数据域和指针域。用链表实现该链表的逆置,并输出。
例如:
输入:5 整数表示要输入的字符个数;
abcde
输出: edcba
注意:不允许通过改变每个节点的数据域来实现效果,必须改变链表连接顺序发生逆置。
我写的代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
struct Node
{
char date;
struct Node *next;
};
struct Node *CreateList();
void Convert(struct Node *head);
void Print(struct Node *head);
void FreeList(struct Node *head);
int main()
{
struct Node *head;
int n;
scanf("%d", &n);
head = CreateList(n);
Convert(head);
Print(head);
FreeList(head);
return 0;
}
struct Node *CreateList(int n)
{
struct Node *p, *q, *head;
int i;
p = (struct Node *)malloc(sizeof(struct Node));
head = p;
q = p;
for(i = 0; i <= n; i++)
{
p = (struct Node *)malloc(sizeof(struct Node));
scanf("%c", &p->date);
q->next = p;
q = p;
}
q->next = NULL;
return head;
}
void Convert(struct Node *head)
{
struct Node *p, *q, *r;
p = head->next;
q = head->next;
r = head;
while(q->next != NULL)
{
q = q->next;
r = r->next;
}
head->next = q;
q->next = r;
while(q != p)
{
q = p;
while(q->next != r)
{
q= q->next;
}
r->next = q;
r = q;
}
p->next = NULL;
return;
}
void Print(struct Node *head)
{
struct Node *p;
p = head->next;
while(p != NULL)
{
printf("%c", p->date);
p = p->next;
}
return;
}
void FreeList(struct Node *head)
{
struct Node *p, *q;
p = head;
while(p != NULL)
{
q = p->next;
free(p);
p = q;
}
return;
}