单链表的基础实现
时间:2006/03/23
测试环境:TC2.0
#include <stdio.h> #define LEN sizeof(struct LNode) #define NULL 0 typedef int ElemType; struct LNode { ElemType data; struct LNode *next; }; /*创建一个带空头结点的单链表*/ struct LNode *CreatList() { struct LNode *head,*p,*temp; head = (struct LNode *)malloc(LEN); p = temp = (struct LNode *)malloc(LEN); printf("input the number:"); scanf("%d",&p->data); head->next = p; while(p->data!=0) { p = (struct LNode *)malloc(LEN); printf("input the number:"); scanf("%d",&p->data); temp->next = p; temp = p; } temp->next = NULL; return head; } /*打印出单链表*/ void Print(struct LNode *head) { struct LNode *p; p = head->next; while(p->next!=NULL) { printf("%d ",p->data); p = p->next; } } /*销毁这个线性表*/ void DestroyList(struct LNode *head) { struct LNode *p,*temp; p = temp = head->next; while(head->next!=NULL) { head->next = p->next; temp = p; free(temp); p = head->next; } } /*在第i个位置前插入新结点*/ void InsertList(struct LNode *head,int i) { struct LNode *p,*insert; int count = 0; p = head; while(count<i-1 && p) { count++; p = p->next; } if(count>i-1 || !p) return; printf("input a number that you want to insert:"); insert = (struct LNode *)malloc(LEN); scanf("%d",&insert->data); insert->next = p->next; p->next = insert; } /*删除第i个结点*/ void DeleteList(struct LNode *head,int i) { struct LNode *p,*temp; int count = 0; p = head; while(count<i-1 && p) { count++; p = p->next; } if(count>i-1 || !p) return; temp = p->next; p->next = temp->next; free(temp); } void main() { struct LNode *L; /*创建链表并打印*/ L = CreatList(); printf("your list is:/n"); Print(L); printf("/n"); /*在第3个结点前插入新结点,并打印*/ InsertList(L,3); printf("now,your list is:/n"); Print(L); printf("/n"); /*删除第4个结点,并打印*/ printf("delete the 4th member,"); printf("now,your list is:/n"); /*销毁链表,并验证是否成功*/ DeleteList(L,4); Print(L); DestroyList(L); if(!L->next) printf("/nyour list has destroyed!"); }
时间: 2024-11-05 20:42:50