#include
#include
#include
#define max_list_length 20
#define expand_list_length 5
using namespace std;
#include
#include
typedef struct Node {
struct Node *next;
int value;
} Node, *List;
///初始化一个list
List init(Node *list) {
if(list == NULL) {
list = (List) malloc(sizeof(Node));
}
list->value = 0;
List tmpList = list;
for (int i = 1;i<=max_list_length; ++i) {
List node = (List) malloc(sizeof (Node));
node->value = i;
tmpList->next = node;
tmpList = node;
}
return list;
}
///输出列表所有元素
void ergodic(Node *list) {
if(list == NULL) {
return;
}
Node * tmpList = list;
while(list != NULL){
printf("%d,",list->value);
list= list->next;
}
printf("\n");
}
///销毁一个链表
List destory(Node* list) {
if(list == NULL) {
return list;
}
int length = 0;
Node *tmpList;
while(list != NULL){
printf("%d,",list->value);
tmpList = list;
list = list->next;
free(tmpList);
++length;
}
printf("\nlist length is :%d",length);
return list;
}
///删掉某个位置的元素,对于特殊位置0要特殊处理
List deleteOnElem(Node* list, int i) {
Node * tmpList = list;
int pos = -1;
while(tmpList->next && ++pos < i - 1) {
tmpList = tmpList ->next;
}
List tmp = tmpList->next;
if(i ==0) {
tmp = tmpList;
list = tmpList->next;
} else {
tmpList->next = tmpList->next->next;
}
if(!(tmpList->next) ) return list;
printf("%d\n",tmp->value);
free(tmp);
return list;
}
///get one position value
Node* getOnePos(Node *list, int i) {
if(list == NULL) {
return NULL;
}
while(list != NULL && --i >-1){
list= list->next;
}
return list;
}
///添加一个元素
Node* addOneElem( Node* list, int i ,int value) {
Node* tmp = (Node*) malloc(sizeof(Node));
tmp->value = value;
if(i == 0) {
tmp->next = list;
return tmp;
}
List tmpList = list;
while(tmpList!= NULL && --i >0){
tmpList= tmpList->next;
}
if(tmpList == NULL || i > 0) {
return list;
}
tmp->next = tmpList->next == NULL ? NULL : tmpList->next->next;
tmpList->next = tmp;
return list;
}
///修改某个地方的值
Node* updateOneElem(Node* list, int i, int value) {
if(list == NULL) {
return NULL;
}
List tmpList = list;
while(tmpList != NULL && --i >-1){
tmpList= tmpList->next;
}
if(tmpList == NULL || i > -1) {
return list;
}
tmpList->value = value;
return list;
}
///逆序单链表
Node* revertList(Node* list) {
if(list == NULL) {
return list;
}
Node* tmp=list->next,*now ;
while(tmp->next ) {
now = tmp->next;
tmp->next = now->next;
now->next = list->next;
list->next = now;
}
return list;
}
int main()
{
List list = NULL;
list = init(list);
ergodic(list);
list = deleteOnElem(list,1);
ergodic(list);
Node* now = getOnePos(list, 0);
printf("%d\n",now->value);
list = addOneElem(list,20,999);
ergodic(list);
list = updateOneElem(list,8,888);
list= revertList(list);
destory(list);
return 0;
}
单链表的简单实现
最新推荐文章于 2022-10-31 22:08:16 发布