1. 程式人生 > 其它 >線性表-TwoLinkList(雙鏈表)

線性表-TwoLinkList(雙鏈表)

知識點
   1:迴圈雙鏈表尾結點指向頭結點
typedef struct TWONode
{
    int data;
    pNode *prev,*next;
} pNode;
int main(int argc, char const *argv[])
{
    int n, element, flag;
    pNode *head, *last;
    /***************************************************************/
    printf("Please input the size of the list:
"); scanf("%d", &n); last = InitList(&head, n);//初始化連結串列並賦值,返回尾節點last printf("%d %d \n", head->next->data, last->data); //列印為第一個元素和最後一個元素 PrintList(head); /***************************************************************/ flag = SearchList(head); //搜尋某個值並刪除節點 if (flag > 0
&& flag <= n) { DelNumqList(&head, flag); PrintList(head); } else printf("Element does not exist, cannot be deleted\n"); /***************************************************************/ DeleteList(&head);//清空列表 PrintList(head); return
0; }

初始化雙鏈表尾插法

pNode *InitList(pNode **head,int n)
{
    pNode *p,*s;
    *head=(pNode *)malloc(sizeof(pNode));
    if(*head==NUll)
    {
        return 0;
    }
    *head->next=NULL;
    *head->prev=NULL;
    p=*head;
    int i;
    for(i=0;i<n;++i)
    {
        s=(pNode *)malloc(sizeof(pNode));
        if(s==0)return 0;
        printf("Input the value of the %dth node:", i + 1);
        scanf("%d",&s->data);
        s->next=NULL;
p
->next=s; s->prev=p; p=s; } return p; }

遍歷列印

void prinList(pNode *head)
{
    pNode *p;
    p=head->next;
    if(head->next==NULL)
    {
        return 0;
    }
    while(p!=NULL)
    {
        printf("%d ",p->data);
        p=p->next;
    }
}

請空連結串列

void delectList(pNode **head)
{
    pNode *p;
    while(*head->next!=NULL)
    {
        p=*head;
        p->next->prev=NULL;
        *head=p->next;
        free(p);
    }
}

查詢

int searchList(pNode *head)
{
    int number;
    printf("Values are about to be deleted:");
    scanf("%d",&number);
    pNode *p;
    p=head->next;
    while(p!=NULL)
    {
        if(p->data==number)
        {
            return number;
        }
        p=p->next;
    }
    return 0;
}

刪除元素

void delNumList(pNode **head,int n)
{
    int i;
    pNode *p;
    p=*head->next;
    for(i=1;i<n;++i)
    {
        p=p->next;
    }
    if(p->next==NULl)//如果p是尾節點則直接將前驅節點指向NULL
    {
        p->prev->next==NULL;
        free(p);
    }
    else//令p的前驅節點和後驅節點相互指向即可
    {
        p->next->prev=p->prev;
        p->prev->next=p->next;
        free(p);
    }
}