数据结构——单人名单
单列表ADT
List makeEmpty(List l);//清空链表,仅仅留头结点
int isEmpty(List l);//推断是否为空
int isLast(List l, Position p);//推断是否是最后一个结点
List createList();//创建一个链表
Position find(List l, Element e);//寻找元素e
void reverse(List l);//链表逆置
void print(List l);//打印链表
#include <stdio.h> #include <stdlib.h> typedef char Element; typedef struct Node { Element value; struct Node* next; } Node, *List, *Position; /* ADT */ void deleteList(); List makeEmpty(List l); int isEmpty(List l); int isLast(List l, Position p); List createList(); void insert(List l, Node *n, Element e); Position find(List l, Element e); Position delete(List l, Element e); void reverse(List l); void print(List l); //delete the list void deleteList(List l) { if (l == NULL) return; Position p, tmp; p = l->next; l->next = NULL; while (p) { tmp = p->next; free(p); p = tmp; } } //empty the list List makeEmpty(List l) { deleteList(l); l->next = NULL; return l; } //judge the is empty?int isEmpty(List l) { return l->next == NULL; } //isLast int isLast(List l, Position p) { return p->next == NULL; } //create a list List createList() { Node *l; l = (Node *) malloc(sizeof(Node)); //create a header Node *r; r = l; char c; while (scanf("%c", &c) != EOF) { Node *n = (Node *) malloc(sizeof(Node)); n->value = c; r->next = n; //get the node to the list r = n; //direct the next node } r->next = NULL; return l; } //find the Node's value == e,else return NULL Position find(List l, Element e) { List tmp = l->next; while (tmp) { if (tmp->value == e) return tmp; tmp = tmp->next; } return NULL; } //delete a node's value equals e and return it;else return null Position delete(List l, Element e) { Position p, tmp = NULL; tmp = l->next; while (tmp) { if (tmp->value == e) { p = tmp; return p; } tmp = tmp->next; } return p; } // insert a node which value is e in the back of Node n void insert(List l, Node *n, Element e) { Node* tmp; tmp = (Node*) malloc(sizeof(Node)); if (tmp == NULL) { printf("Error!!!"); return; } tmp->value = e; tmp->next = n->next; n->next = n; } //reverse the List remember it ,very important! void reverse(List l) { if(l == NULL || l->next == NULL)return; Position pcur, pre, pnext; pre = NULL; pcur = l->next; //direct the head's next node pnext = NULL; while (pcur) { pnext = pcur->next; //record the next node pcur->next = pre; //direct the pre node pre = pcur; //pre node direct completed subList pcur = pnext; //completing the next node } l->next = pre; } //print the list void print(List l){ if(l == NULL || l->next == NULL)return; Position tmp = l->next; while(tmp){ printf("%c", tmp->value); tmp = tmp->next; } } //test int main(int argc, char **argv) { List l = createList(); reverse(l); print(l); return 0; }
版权声明:本文博主原创文章,博客,未经同意不得转载。