无头结点的单链表的创建和逆置
程序员文章站
2022-06-06 13:40:07
...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node{
int data;
struct node* next;
}Node;
Node* CreateList(void)
{
int val,i,n;
Node *head,*p,*q;
head = NULL;
printf("请输入你要建立的链表的长度:\n");
scanf("%d",&n);
printf("请输入你要输入的数据:\n");
for(i=0; i<n; i++)
{
scanf("%d",&val);
p = (Node*)malloc(sizeof(Node));
p->data = val;
if(head == NULL)
{
head=q=p;
}
else
q->next = p;
q=p;
}
q->next = NULL;
return head;
}
void showlist(Node* head)
{
Node* p;
p=head;
while(p)
{
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}
//链表的逆置
Node* ReverseList(Node* head)
{
Node* p,*q,*r;
p=head;
q=r=NULL;
while(p)
{
q = p->next; //q保存的是p下一个结点的指针
p->next = r; //p指向r
r = p;
p = q;
}
return r;
}
int main()
{
Node *head;
head = CreateList();
showlist(head);
head = ReverseList(head);
showlist(head);
//printf("HelloWorld!\n");
return 0;
}
运行效果:
上一篇: python学习第一天
下一篇: PHP 开发工具_php文摘
推荐阅读