一、单向链表
#include <stdio.h> #include <stdlib.h> #define FALSE 0 #define TRUE 1 //#include "link.h" typedef struct NODE { struct NODE *link; int value; }Node; //createNode() Node * createNode(int value) { Node *node; node = (Node*)malloc(sizeof(Node)); if(node!=NULL) { node->value = value; node->link = NULL; } else { printf("Not Enough Memory!\n"); } } //sortinsert() int sortInsert(register Node**linkp,int new_value) { register Node *current; register Node *new; while((current = *linkp)!=NULL && current->value<new_value) linkp = ¤t->link; new = (Node*)malloc(sizeof(Node)); if(new == NULL) return FALSE; new->value = new_value; new->link = current; *linkp = new ; return TRUE; } //freeLinkList() void freeLinkList(Node * head) { if(head == NULL) { printf("\n Empty memory! \n"); return; } Node *ptr = head; Node * curr; while(ptr->link != NULL) { curr = ptr; ptr = ptr->link; free(curr); } free(ptr); } //printLinkList() void printLinkList(Node * head) { if(head == NULL) return; while(head->link != NULL) { head = head->link; printf("%d -> ",head->value); } putchar('\n'); } //main() int main(int argc, char *argv[]) { Node * head; head = (Node*)malloc(sizeof(Node)); int i; for(i=0;i<10;i++) { Node * newNode = createNode(i); newNode->link = head->link; head->link = newNode; } printLinkList(head); sortInsert(&head->link,13); sortInsert(&head->link,10); printLinkList(head); freeLinkList(head); system("PAUSE"); return 0; }
二、双向链表
#include<stdio.h> #include<stdlib.h> #define FALSE 0 #define TRUE 1 typedef struct NODE { struct NODE *fwd; struct NODE *bwd; int value; }Node; //插入节点 int dll_insert(register Node * rootp,int value) { register Node * this; register Node * next; register Node * newnode; for(this =rootp;(next = this->fwd)!=NULL;this = next) { if(next->value == value) return FALSE; if(next->value > value) break; } newnode = (Node*)malloc(sizeof(Node)); if(newnode == NULL) return -1; newnode->value = value; /*插入新节点*/ newnode->fwd = next; this->fwd =newnode; newnode->bwd = this != rootp ? this : NULL; (next != NULL ? next:rootp)->bwd = newnode; return 1; } //打印链表 void printLinklist(Node * rootp) { if(rootp == NULL) return; Node * temp = rootp; while(temp->fwd != NULL) { temp = temp->fwd; printf("%d->",temp->value); } printf("NULL\n"); } //释放链表空间 void freeLinkList(Node * rootp) { if(rootp == NULL) { printf("\n Empty memory! \n"); return; } Node *ptr = rootp; Node * curr; while(ptr->fwd != NULL) { curr = ptr; ptr = ptr->fwd; free(curr); } free(ptr); } //main int main(int argc, char *argv[]) { Node * rootp; rootp = (Node*)malloc(sizeof(Node)); rootp->bwd = NULL; rootp->fwd = NULL; int i; for(i=0;i<10;i++) { dll_insert(rootp,i); } printLinklist(rootp); freeLinkList(rootp); system("PAUSE"); return 0; }