遍历双向链表

在每个数据结构的情况下,遍历是最常见的操作。 为此,将头指针复制到临时指针ptr中。

ptr = head;

然后,使用while循环遍历链表。继续移动指针变量ptr的值,直到找到最后一个节点。 最后一个节点的next指针指向null

while(ptr != NULL)  
{  
    printf("%d\n",ptr->data);  
    ptr=ptr->next;  
}

遍历意味着访问列表的每个节点一次以执行某些特定操作。 在这里,遍历打印链表的每个节点相关联的数据。

算法

第1步:IF HEAD == NULL
   提示 “UNDERFLOW”
   转到第6步
  [IF结束]

第2步:设置PTR = HEAD
第3步:重复第4步和第5步,同时PTR!= NULL
第4步:打印 PTR→data 的值
第5步:PTR = PTR→下一步
第6步:退出

C语言实现的示例代码 -

#include<stdio.h>  
#include<stdlib.h>  
void create(int);
int traverse();
struct node
{
    int data;
    struct node *next;
    struct node *prev;
};
struct node *head;
void main()
{
    int choice, item;
    do
    {
        printf("1.Append List\n2.Traverse\n3.Exit\n4.Enter your choice?");
        scanf("%d", &choice);
        switch (choice)
        {
        case 1:
            printf("Enter the item\n");
            scanf("%d", &item);
            create(item);
            break;
        case 2:
            traverse();
            break;
        case 3:
            exit(0);
            break;
        default:
            printf("Please enter valid choice\n");
        }

    } while (choice != 3);
}
void create(int item)
{

    struct node *ptr = (struct node *)malloc(sizeof(struct node));
    if (ptr == NULL)
    {
        printf("OVERFLOW\n");
    }
    else
    {
        if (head == NULL)
        {
            ptr->next = NULL;
            ptr->prev = NULL;
            ptr->data = item;
            head = ptr;
        }
        else
        {
            ptr->data = item;printf("\nPress 0 to insert more ?\n");
            ptr->prev = NULL;
            ptr->next = head;
            head->prev = ptr;
            head = ptr;
        }
        printf("Node Inserted\n");
    }

}
int traverse()
{
    struct node *ptr;
    if (head == NULL)
    {
        printf("Empty List\n");
    }
    else
    {
        ptr = head;
        while (ptr != NULL)
        {
            printf("%d\n", ptr->data);
            ptr = ptr->next;
        }
    }
}

执行上面示例代码,得到以下结果 -

1.Append List
2.Traverse
3.Exit
4.Enter your choice?1

Enter the item
23

Node Inserted
1.Append List
2.Traverse
3.Exit
4.Enter your choice?1

Enter the item
23

Press 0 to insert more ?

Node Inserted
1.Append List
2.Traverse
3.Exit
4.Enter your choice?1

Enter the item
90

Press 0 to insert more ?

Node Inserted
1.Append List
2.Traverse
3.Exit
4.Enter your choice?2
90
23
23

上一篇: 双链表 下一篇: 循环单向链表