实现将一个单链表反转,并输出反转后的单链表。
#include <stdio.h>
#include <malloc.h>
struct stud {
int num ;
struct stud *next ;
} ;
// 核心函数:反转单链表
void reverse (struct stud * head)
{
struct stud *cur , *p ;
cur = head->next ;
head->next = NULL ; // 形成新链表
while (cur) {
p = cur->next ;
// 插入cur节点
cur->next = head->next ;
head->next = cur ;
// cur指向后续节点p继续循环
cur = p ;
}
}
// 创建单链表
struct stud * create (void)
{
struct stud *head, *p, *q ;
head = p = (struct stud * )malloc(sizeof(struct stud)) ;
q = (struct stud *)malloc(sizeof(struct stud)) ;
scanf ("%d", &q->num) ;
while (q->num!=0) {
p->next = q ;
p = q ;
q = (struct stud *) malloc (sizeof(struct stud)) ;
scanf ("%d", &q->num) ;
}
p->next = NULL ;
free(q) ;
return head ;
}
// 输出单链表
void Print (struct stud * head)
{
struct stud *p = head->next ;
while (p) {
printf ("%d ", p->num) ;
p = p->next ;
}
printf ("\n") ;
}
int main (void)
{
struct stud *head ;
// 创建链表
head = create () ;
Print(head) ;
// 反转链表
reverse(head) ;
Print(head) ;
return 0 ;
}
注意:链表之类相关代码,需要在草稿纸上整理好思路再动手!要细心!注意插入删除不丢失后续节点!!!