您好我正在尝试实现一个通用链表。我已经使用以下代码进行了一些工作,但是我看不到一种明显而简洁的方法来消除对全局指针(curr 和 root)的依赖,从而允许定义多个链表。如果我使用的是 c++,我可能只是将整个东西包装在一个类中,但实际上我只能看到一个解决方案,它是手动处理并将 root 和 curr 传递给需要它们的函数。我敢肯定有比这更好的方法,所以你会怎么做。谢谢
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
struct Node{
int value;
struct Node *next;
};
struct Node * curr = NULL;
struct Node * root = NULL;
struct Node * createList(int val){
struct Node *n = malloc(sizeof(struct Node));
if(n==NULL){
printf("Node creation failed\n");
return NULL;
}
n->value = val;
n->next = NULL;
root=curr=n;
return n;
}
struct Node * extendList(int val, bool end){
if(curr == NULL){
return createList(val);
}
struct Node * newNode = malloc(sizeof(struct Node));
if(newNode==NULL){
printf("Node creation failed\n");
return NULL;
}
newNode->value = val;
newNode->next = NULL;
if(end){
curr->next = newNode;
curr = newNode;
}
else{
newNode->next = root;
root=newNode;
}
return curr;
}
void printList(void){
struct Node *ptr = root;
while(ptr!=NULL){
printf("%d\n",ptr->value);
ptr = ptr->next;
}
return;
}
struct Node * pos_in_list(unsigned int pos, struct Node **prev){
struct Node * ptr = root;
struct Node * tmp = NULL;
unsigned int i = 0;
while(ptr!=NULL){
if(i == pos){
break;
}
tmp = ptr;
ptr=ptr->next;
i++;
}
*prev = tmp;
return ptr;
}
void deletefromlist(int pos){
struct Node * del = NULL;
struct Node * prev = NULL;
del = pos_in_list(pos,&prev);
if(del == NULL)
{
printf("Out of range\n");
}
else
{
if(prev != NULL)
prev->next = del->next;
if(del == curr)
{
curr = prev;
}
else if(del == root)
{
root = del->next;
}
}
free(del);
del = NULL;
}
void deleteList(){
struct Node * del = root;
while(curr!=NULL){
curr = del->next;
free(del);
del=curr;
}
root = NULL;
curr = NULL;
}
int main(void)
{
int i;
for(i=0;i<10;i++){
extendList(i,true);
}
for(i=10;i>0;i--){
extendList(i,false);
}
printList();
deletefromlist(5);
printList();
deleteList();
return 0;
}