程序不能只是看,而不动手写。动手写,要自己写,而不能看着书上的代码来抄。
今天写那个单链表就是比较的悲剧。
下面是自己写的。
这个单链表有 头节点。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct student
{
int data;
struct student *next;
}node;
node *create()
{
node *head, *s, *p;
int x, cycle = 1;
head = (node *)malloc( sizeof(node) );
p = head;
while( cycle )
{
printf( "please input the data\n" );
scanf( "%d",&x );
if( x != 0 )
{
s = ( node * )malloc( sizeof( node ) );
s->data = x;
p->next = s;
p = s;
}
else
cycle = 0;
}
p->next = NULL;
return head;
}
node *print( node *head )
{
node *q;
q = head->next;
while( q )
{
printf( "%d", q->data);
q = q->next;
}
printf( "\n" );
}
int length( node *head )
{
node *q;
q = head->next;
int length = 0;
printf( "now the length of head is ...\n" );
while( q )
{
length++;
q = q->next;
}
return length;
}
node * reverse( node * head )
{
if( head->next == NULL || head->next->next == NULL )
return head;
node *p1, *p2, *p3;
p1 = head->next;
p2 = p1->next;
p1->next = NULL;
while( p2 )
{
p3 = p2->next;
p2->next = p1;
head->next = p2;
p1 = p2;
p2 = p3;
}
return head;
}
int main()
{
node *head;
head = create();
print( head );
printf( "\n%d\n",length(head) );
reverse( head );
print( head );
}