/*通用列表的链接实现,用currentPos和current保存当前位置
从而加快速度*/
typedef int ListEntry;
typedef struct listnode{ //节点
ListEntry entry;
struct listnode* next;
}ListNode;
typedef int Position;
typedef struct list{ //链表结构
int count;
ListNode* head;
Position currentpos; //当前位置
ListNode* current; //当前位置指针
}List;
void CreateList(List*);
int ListEmpty(List*);
void SetPosition(Position p,List *list); //定位p位置
void InsertList(Position p,ListEntry x,List *list);
ListNode *MakeListNode(ListEntry x);
void TraverseList(List*,void (*visit)(ListEntry));
void Print(ListEntry);
void DeleteList(Position,ListEntry*,List*);
void CreateList(List* list)
{
list->count=0;
list->head=NULL;
list->currentpos=-1;
list->current=NULL;
}
int ListEmpty(List *list)
{
return list->count==0;
}
void SetPosition(Position p,List *list)
{
if(p<0||p>=list->count)
printf("Attempt to set a position not in the list.");
else{
if(pcurrentpos){
list->currentpos=0;
list->current=list->head;
}
for(;list->currentpos!=p;list->currentpos++)
list->current=list->current->next;
}
}
ListNode *MakeListNode(ListEntry x)
{
ListNode *p=malloc(sizeof(ListNode));
if(p){
p->entry=x;
p->next=NULL;
}
else
printf("No space for additional node can be obtained.");
return p;
}
void InsertList(Position p,ListEntry x,List *list)
{
ListNode *newnode;
if(p<0||p>list->count)
printf("Attempt to insert in a position not in the list.");
else{
newnode=MakeListNode(x);
if(p==0){
newnode->next=list->head;
list->head=newnode;
list->currentpos=p;
list->current=list->head;
}
else{
SetPosition(p-1,list);
newnode->next=list->current->next;
list->current->next=newnode;
list->currentpos=p;
list->current=list->current->next;
}
list->count++;
}
}
void TraverseList(List* list,void (*visit)(ListEntry))
{
ListNode *p;
p=list->head;
while(p)
{
visit(p->entry);
p=p->next;
}
}
void Print(ListEntry x)
{
printf("%d ",x);
}
void DeleteList(Position p,ListEntry* x,List *list)
{
ListNode *temp;
if(p<0||p>=list->count)
printf("Attemp to delete in a position not in the list.\n");
else if(ListEmpty(list))
printf("The list is empty!\n");
else
{
if(p==0)
{
temp=list->head;
list->head=list->head->next;
}
else
{
SetPosition(p-1,list);
//
printf("mark:curpos:%d\n",list->currentpos);
temp=list->current->next;
list->current->next=temp->next;
}
*x=temp->entry;
free(temp);
list->count--;
}
}