您的位置:首页 > 其它

双向链表的基本操作

2015-01-06 10:42 190 查看
双向链表的第个结点有两个指针,分别指向其直接前驱结点和直接后驱结点。这样就可以从表中任意的元素结点出发,从两个方向遍历链表。

1、双向链表结构体声明

typedef struct Node
{
    int data;
    struct Node *front;
    struct Node *next;
}Node;


2、尾插法构造带头结点双向链表

Node * createDLL_ByTail()//尾插法构造带头结点的双向链表
{
    Node *p,*r,*head;
    int x;
    head=(Node *)malloc(sizeof(Node));
    head->front=NULL;
    r=head;
    while(scanf("%d",&x)!=EOF)
    {
        p=(Node *)malloc(sizeof(Node));
        p->data=x;
        r->next=p;
        p->front=r;
        r=p;
    }
    r->next=NULL;
    return head;
}

结尾的r->next=NULL;一定不能少。不然出现内存泄露。

3、头插法构造带头结点双向链表

Node * createDLL_ByHead()//头插法构造带头结点的双向链表
{
    Node *p,*r,*head;
    int x;
    head=(Node *)malloc(sizeof(Node));
    r=NULL;
    head->front=NULL;
    while(scanf("%d",&x)!=EOF)
    {
        p=(Node *)malloc(sizeof(Node));
        p->data=x;
        p->next=r;
        if(r==NULL)
            r=(Node *)malloc(sizeof(Node));
        r->front=p;
        r=p;
    }
    p->front=head;
    head->next=r;
    return head;
}
返回之前的最后两句也不能少。不然出现指针指向未知。

4、双向链表的正向遍历

void positivePrintDLL(Node *head)//双向链表的正向遍历
{
    if(head->next==NULL)
        printf("This is a empty doubly link list\n");
    while(head->next)//means head->next!=NULL
    {
        head=head->next;
        printf("%d ",head->data);
    }
}

while()循环体两条语句不可以互换,可以修改为: printf("%d ",head->next->data); head=head->next;

5、双向链表的反向遍历

void reversePrintDLL(Node *tail)//双向链表的反向遍历
{
    if(tail->front==NULL)
        printf("This is a empty doubly link list\n");
    while(tail->front)//means head->next!=NULL
    {
        printf("%d ",tail->data);
        tail=(*tail).front;
    }
}


while()循环体两条语句不可以互换,应先输出后,再向前移进。

6、在结点p前插入结点s

s->front=p->front;
p->front->next=s;//或者s->front->next=s;
s->next=p;
p->front=s;

第三句与第四句可以互换,但第一句与第二句互换就只能:p->front->next=s;s->front=p->front;

7、在结点p后插入结点s

s->next=p->next;
p->next->front=s;//或者s->next->front=s;
s->front=p;
p->next=s;

第三句与第四句可以互换,但第一句与第二句互换就只能:p->next->front=s;s->next=p->next;

8、删除p结点

p->next->front=p->front;
p->front->next=p->next;
free(p);


第一句与第二句的位置可以互换。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: