- 首页 > it技术 > >
#include
#include
#include #define ok 1
#define error 0struct linklist
{
int id;
struct linklist *next;
};
int init_linklist(struct linklist **head);
int insert_linklist(struct linklist *head);
int traver_linklist(struct linklist *head);
int chang_linklist(struct linklist **head);
int main(int argc,char *argv[])
{
int i=0;
struct linklist *head;
init_linklist(&head);
while (i < 5)
{
insert_linklist(head);
i++;
}
traver_linklist(head);
chang_linklist(&head);
traver_linklist(head);
return ok;
}int init_linklist(struct linklist **head)
{
*head = (struct linklist *)malloc(sizeof(struct linklist));
if (NULL == (*head))
{
printf("init error\n");
return error;
} memset(*head,0,sizeof(struct linklist));
(*head)->next = NULL;
return ok;
}int insert_linklist(struct linklist *head)
{
struct linklist *s;
struct linklist *p = head->next;
struct linklist *upper = head;
s = (struct linklist *)malloc(sizeof(struct linklist));
if (NULL == s)
{
printf("init error\n");
return error;
}
memset(s,0,sizeof(struct linklist));
printf("please input the num:\t");
scanf("%d",&s->id);
s->next = NULL;
while ( p != NULL&& p->id id)
{
upper = p;
p = p->next;
}
s->next = p;
upper->next = s;
return ok;
}int traver_linklist(struct linklist *head)
{
struct linklist *p;
p = head->next ;
while ( p!= NULL)
{
printf("%d--",p->id);
p = p->next;
}
printf("\n");
}int chang_linklist(struct linklist **head) //实现单链表的就地逆转
{
struct linklist *p = (*head)->next;
struct linklist *q = NULL;
struct linklist *r = NULL;
while (p!= NULL)
{
q = p->next;
p->next = r;
r = p;
p = q;
}// free(*head);
// *head = NULL;
(*head)->next = r;
}
推荐阅读