赞
踩
#include <stdio.h> #include <stdlib.h> #define DataType int /* * LinkedList */ typedef struct node { DataType data; struct node* next; }LinkList; void initList(LinkList *list) { if (list != NULL) { list = (LinkList*) malloc(sizeof(LinkList)); } } void addHead(LinkList *list, int data) { if (list == NULL) { initList(list); } LinkList *p; p = (LinkList*) malloc(sizeof(LinkList)); p -> data = data; p -> next = list -> next; list -> next = p; } LinkList* createLinkListByTail(int data[]) { int size = sizeof(data) / sizeof(int); LinkList *list; LinkList *tail, *temp; for(int i = 0;i < size;i ++) { int d = data[i]; temp = (LinkList*) malloc(sizeof(LinkList)); temp -> data = d; if(list == NULL) { list = temp; tail = temp; } else { tail -> next = temp; tail = temp; } } return list; } int getLength(LinkList* list) { int length = 0; LinkList *temp = list; while(temp != NULL) { length ++; temp = temp -> next; } return length; } DataType getDataByPos(LinkList *list, int pos) { LinkList *iterator = list; for(int i = 0;i < pos && iterator != NULL;i ++) { iterator = iterator -> next; } if(iterator != NULL) { return iterator -> data; } else { return NULL; } } DataType* getData(LinkList* list) { int length = getLength(list); DataType data[length]; LinkList *temp = list; int iterator = 0; while(temp != NULL) { data[iterator ++] = temp -> data; temp = temp -> next; } return data; } /* * 向链表中插入元素 * 注: pos从0开始 */ int insertData(LinkList* list, int pos, DataType data) { LinkList *iterator = list, *temp = (LinkList*) malloc(sizeof(LinkList)); int insertFlag = 1; for(int i = 0;i < pos && iterator != NULL;i ++) { iterator = iterator -> next; } if(iterator != NULL) { temp->data = data; temp->next = iterator->next; iterator->next = temp; } else { insertFlag = 0; } return insertFlag; } /* * 删除链表中元素 * 注: pos从0开始 */ int deleteData(LinkList* list, int pos) { LinkList *iterator = list; LinkList *pre_iterator; int deleteFlag = 0; for(int i = 0;i < pos && iterator != NULL;i ++) { pre_iterator = iterator; iterator = iterator -> next; } if(iterator != NULL) { deleteFlag = 1; pre_iterator -> next = iterator -> next; free(iterator); } else { deleteFlag = -1; } return deleteFlag; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。