面试宝典之单链表操作

来源:互联网 发布:淘宝软文书籍 编辑:程序博客网 时间:2024/04/29 21:53

下面的代码,包含了面试宝典的

13.1章节,即单链表的代码,所以以后要多写代码。


#include <stdio.h>#include <stdlib.h>#include <string.h>typedef struct student {intdata;struct student  *next;}node;node *create(){node  *head, *s, *p;intx, 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;}node * sort( node * head ){if( head->next == NULL || head->next->next == NULL )return head;int n = length( head );int i , j, temp;node *p ,*q;for( i = 1; i < n ;i++ ){p = head;for( j= 0; j< n - i ; j++ ){if( p->data > p->next->data ){temp = p->data;p->data = p->next->data;p->next->data = temp;}p = p->next;}}return head;}node *del( node *head, int num ){node *p1, *p2, *p3;p1 = head;while( num != p1->data && p1->next != NULL ){p2 = p1;p1 = p1->next;}if( num == p1->data ){if( p1 == head->next ){head = p1->next;free( p1 );} else{p2->next = p1->next;free(p1);}}elseprintf( "oh ,Can't find the num ...\n" );}node *insert( node *head, int num ){node *p0, *p1, *p2;p1 = head;p0 = ( node * )malloc( sizeof( node ) );p0->data = num;while( p0->data > p1->data && p1->next != NULL ){p2 = p1; p1 = p1->next;}if( p0->data <= p1->data ){if( p1 == head->next ){p0->next = head->next;head = p0;}else{p0->next = p1;p2->next = p0;}}else{p1->next = p0;p0->next = NULL;}return head;}void remove_head( node *head ){node *p1;p1 = head->next;head->next = p1->next;free( p1 );}int find_middle( node *head ){node *p1, *p2;p1 = p2 = head;while( p2 ){p2 = p2->next->next;p1= p1->next;}return p1->data;}int main(){node *head;head = create();print( head );//del( head, 44 );//print( head );/*printf( "startig inserting....\n" );insert( head, 44 );print( head );printf( "begine to remove_head ...\n" );remove_head( head );print( head );*/printf( "find the middle...\n" );printf( "%d.\n",find_middle( head ) );//printf( "\n%d\n",length(head) );//reverse( head );//print( head );//sort( head );//print( head );//printf( "after sort...\n" );//insert( head, 44 );//print( head );}