遍历一次把单链表反转
#include <stdio.h>
#include <stdlib.h>typedef struct student {
int num;
struct student *next;
}List;
List *creat_list(void) /*创建链表,当输入0的时候就结束*/
{
int n = 0;
List *head;
List *p1,*p2;
p1=p2=(List*)malloc(sizeof(struct student));
scanf("%d",&p1->num);
head = NULL;
while(p1->num!=0)
{
n = n+1;
if(1==n)
head = p1;
else
p2->next = p1;
p2 = p1;
p1 = (List*)malloc(sizeof(struct student));
scanf("%d",&p1->num);
}
p2->next = NULL;
return head;
}
void print_list(List *head) /*打印链表*/
{
List *p;
p = head;
do{
printf("num is:%d\n",p->num);
p = p->next;
}while(p);
}
List *reverse_list(List *head)/*反转链表*/
{
List *h,*cur,*fellow; //h指向头节点,cur指向当前节点,fellow指向当前节点的下一个
h = head;
cur = h->next;
fellow = cur->next;
h->next = NULL; //设置链表的结尾
while(cur)
{
cur->next = h; //把当前节点的next指向h,
h = cur; //h向前推移
cur = fellow;//当前节点指向下一个节点
if(cur)//如果fellow不是NULL
fellow = fellow->next;
}
return h;
}
int main(int argc, char **argv)
{
List *h;
List *head;
h = creat_list();
print_list(h);
head = reverse_list(h);
printf("After reverse:\n");
print_list(head);
return 0;
}