Open bosthhe1 opened 2 years ago
主函数
void TestSList1() { SList *Slist = NULL; SListSentry(&Slist); SListPopTail(Slist, 1); SListPopTail(Slist, 2);//尾插2 SListPopHead(Slist, 2); SListPopHead(Slist, 3);//头插3 SListPopinsert(Slist, 2,3);//在2的后面插入3 SListPopDelet(Slist);//删除链表,只留下哨兵位 SListPopPorint(Slist); } int main() { TestSList1(); return 0; }
函数定义
void SListSentry(SList *Head) { SList head = (SList )malloc(sizeof(SList)); head->next = head; head->prev = head; Head = head; } void SListPopTail(SList Slist, int x) { assert(Slist); SList tail = Slist->prev; SListPopinsert(tail, tail->x, x); //SList Head = (SList )malloc(sizeof(SList)); //Head->x = x; //Head->next = Slist; //Head->prev = tail; //tail->next = Head; //Slist->prev = Head; } void SListPopPorint(SList Slist) { SList SList = Slist;
while (Slist->next != SList)
{
printf("%d ", Slist->next ->x);
Slist = Slist->next;
}
} void SListPopHead(SList Slist, int x) { SList NewHead = (SList )malloc(sizeof(SList)); SList Head = Slist->next; SListPopinsert(Head, Head->x, x); /NewHead->x = x; NewHead->next = Head; Head->prev = NewHead; Slist->next = NewHead; NewHead->prev = Slist;/ } void SListPopinsert(SList Slist, int x, int y) { assert(Slist); SList Insert = Slist; while (Insert->x != x) { Insert = Insert->next; } SList Next = Insert->next; SList newnode = Slist; newnode = (SList )malloc(sizeof(SList)); newnode->x = y; newnode->next = Next; newnode->prev = Insert; Insert->next = newnode; Next->prev = newnode; } void SListPopDelet(SList Slist) { assert(Slist); SList head= Slist; SList cur = Slist->next; SList* Next = cur->next; while (cur->next != Slist->next) { head->next = cur->next; Next->prev = head; free(cur); cur = Next; Next = Next->next; } //删掉全部,只留哨兵头 }
函数声明
typedef int Date; typedef struct SList { SList prev; SList next; Date x; }SList; void SListSentry(SList *Slist); void SListPopTail(SList Slist, int x); void SListPopHead(SList Slist, int x); void SListPopinsert(SList Slist, int x, int y); void SListPopPorint(SList Slist); void SListPopDelet(SList Slist);
在结构体指针中存在两个地址,先创建一个哨兵头,结构体指针中一个存放prev(前一个地址),一个存放next(后一个地址),prev存放前一个节点的地址,next存放后一个节点的地址,这样可以向前访问也可以向后访问,形成一个循环 需要注意的是在创建哨兵头的时候,需要使用二级指针