单链表的创建及其反转函数

 

单链表的创建、插值、删除

 

递归及非递归算法实现的单链表反转 

 

/** * @author: J.S.Leaf * @workname: 单链表 * @env: VC6.0 * @time: 2010-07-18 */ // 增加了反转函数的三种实现方法,并且修改了原版本的指针问题 #include <stdio.h> #include <stdlib.h> #include <malloc.h> typedef struct LNode{ char data; struct LNode *next; }LNode,*LinkList; LinkList head; // 头指针 //---------------------------------------------------------- LinkList Create(){ char c; LNode *p; p = (LinkList)malloc(sizeof(LNode)); p->next = NULL; head = p; while((c=getchar())!='/n'){ p = (LinkList)malloc(sizeof(LNode)); p->data = c; p->next = head->next; head->next = p; } return head; } //---------------------------------------------------------- int Insert(int i,char e){ LNode *p,*s; int j=0; p=head; while(p&&j<i-1){ p=p->next; j++; } if(!p||j>i-1) exit(0); s=(LinkList)malloc(sizeof(LNode)); s->data=e; s->next=p->next; p->next=s; return 1; } //---------------------------------------------------------- int Delete( int i ){ LNode *p,*s; int j = 0; p = head; while( p && j < i-1) { p = p->next; j++; } if(!p||j>i-1) exit(0); s = p->next; p->next = s->next; free(s); return 1; } //---------------------------------------------------------- int Reverse_1() // 缺陷是增加了存储空间(一个结构单元) { LNode *p, *q, *e; if( head->next == NULL ) return 0; p = head->next; q = (LinkList)malloc(sizeof(LNode)); q->next = NULL; while( p->next != NULL ) { e = p; p = p->next; head->next = e->next; e->next = q->next; q->next = e; } p->next = q->next; q->next = p; head->next = q->next; return 1; } //---------------------------------------------------------- int Reverse_2() // 推荐算法2 { LNode *p, *e; if( head->next == NULL ) return 0; p = head->next; head->next = NULL; while( p->next != NULL ) { e = p; p = p->next; e->next = head->next; head->next = e; } p->next = head->next; head->next = p; return 1; } //---------------------------------------------------------- LinkList reverse( LNode* p, LNode* &phead ) { if(p == NULL || p->next == NULL) { phead = p; return p; } else { LNode* tmp = reverse( p->next, phead ); tmp->next = p; return p; } } int Reverse_3() // 递归实现,不推荐 { LNode *p, *phead; p = head->next; reverse( p, phead ); head->next = phead; p->next = NULL; return 1; } //---------------------------------------------------------- int Display(){ LNode *p; p = head; while( (p->next) != NULL ){ printf("%c", p->next->data); p = p->next; } printf("/n"); return 1; } //---------------------------------------------------------- int main() { Create(); Display(); Insert(3,'A'); Display(); Reverse_3(); Display(); getchar(); return 0; } /* end of code */

你可能感兴趣的:(算法,struct,null,delete,存储,insert)