单链表基本操作代码
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h> #include <stdlib.h> typedef struct List { struct List *next; int data; }List; List *creatList(int *arr, int len) { List *head, *p; List *s; int i; head = (List *)malloc(sizeof(List)); head->next = NULL; p = head; for(i = 0; i < len; i++) { s = (List *)malloc(sizeof(List)); s->data = arr[i]; s->next= p->next; p->next = s; p = s; } p->next = NULL; head = head->next; return head; } //insert node before value. List *insertNodeBefore(List *list, int value) { List *p, *q; List *node; p = list; while(NULL != p && p->data != value) { q = p; p = p->next; } if(NULL == p) { printf("list has nod %d!\n", value); return list; } node = (List *)malloc(sizeof(List)); node->data = 0; node->next = p; q->next = node; return list; } List *deleteNode(List *list, int value) { List *p, *q; p = list; while(NULL != p && p->data != value) { q = p; p = p->next; } if(NULL == p) { printf("list has not %d\n", value); return list; } q->next= p->next; free(p); return list; } List *revList(List *list) { List *p1 = list; List *p2 = list; List *p3 = list; if(NULL == list || NULL == list->next) { printf("list is Null!\n"); return list; } p2 = p1->next; while(NULL != p2) { p3 = p2->next; p2->next = p1; p1 = p2; p2 = p3; } list->next = NULL; list = p1; return list; } void printList(List *list) { if(NULL == list) { printf("list is NULL!\n"); return; } while(NULL != list) { printf("%d\n", list->data); list = list->next; } } void freeList(List *list) { List *head; head = list; while(NULL != head) { list = head->next; free(head); head = list; } free(list); } int main(int argc, char *argv[]) { int arr[] = {3,5,6,2,8,10}; List *list; list = creatList(arr, 6); printf("=========createList=========\n"); printList(list); printf("=========createList=========\n"); list = insertNodeBefore(list, 8); printf("=========insertNodeList=========\n"); printList(list); printf("=========insertNodeList=========\n"); list = deleteNode(list, 5); printf("=========deleteList=========\n"); printList(list); printf("=========deleteList=========\n"); list = revList(list); printf("=========revList=========\n"); printList(list); printf("=========revList=========\n"); freeList(list); return 0; }