线性链表逆置c语言算法
#include<stdio.h>#include<malloc.h>
struct node
{
char data;
struct node * next;
};
struct node * creat(void);
void InverseList(struct node * head);
void print(struct node * head);
int main(void)
{
struct node * head = NULL;
head = creat();
print(head);
InverseList(head);
print(head);
system("pause");
}
struct node * creat(void)
{
struct node * head = (struct node *)malloc(sizeof(struct node));
struct node * tail = head;
tail->next = NULL;
char c;
int flag = 1;
printf("You want to invert squence: ");
while(flag)
{
c = getchar();
if(c != '\n')
{
struct node * recieve = (struct node *)malloc(sizeof(struct node));
recieve->data = c;
tail->next = recieve;
recieve->next = NULL;
tail = recieve;
}
else
{
flag = 0;
tail->next = NULL;
}
}
return head;
}
void InverseList(struct node * head)
{
struct node * p = head->next; // 定义两个指针指向第一个元素
struct node * q = head->next;
q = q->next; //q保存下一个元素的地址
p->next = NULL; //断开第一个和第二个元素的指针
p = q; //p指向下一个元素 p和q同时指在第二个元素
while(p != NULL)
{
q = q->next; //q保存下一个元素的地址
p->next = head->next; //插入p当前指向的元素在当前头指针之后,也就是第一个位置插入
head->next = p; //和上一句一起完成插入
p = q; //p和q再次同时指向同一个元素
}
}
void print(struct node * head)
{
struct node * p = head->next;
while(p)
{
printf("%c",p->data);
p = p->next;
}
printf("\n");
}
看看学习学习 很难,看不懂 支持鱼C!支持论坛! 谢谢你的测试
先标记, 以后有空再看看
页:
[1]