在每個數據結構的情況下,遍曆是最常見的操作。 為此,將頭指針複製到臨時指針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