遍曆是在單鏈表中執行的最常見操作。 遍曆表示訪問鏈表的每個節點一次,以便對其執行某些操作。這將通過使用以下語句來完成。
ptr = head;
while (ptr!=NULL)
{
ptr = ptr -> next;
}
演算法
第1步:設置PTR = HEAD
第2步:如果PTR = NULL
提示“空鏈表”
轉到第7步
結束條件
第4步:重複第5步和第6步直到PTR!= NULL
第5步:列印PTR→DATA
第6步:PTR = PTR→NEXT
[迴圈結束]
第7步:退出
C語言示例代碼 -
#include<stdio.h>
#include<stdlib.h>
void create(int);
void traverse();
struct node
{
int data;
struct node *next;
};
struct node *head;
void main()
{
int choice, item;
do
{
printf("1.Append List\n");
printf("2.Traverse\n");
printf("3.Exit\n");
printf("4.Enter your choice ? ");
scanf("%d", &choice);
switch (choice)
{
case 1:
printf("\nEnter the item\n");
scanf("%d", &item);
create(item);
break;
case 2:
traverse();
break;
case 3:
exit(0);
break;
default:
printf("\nPlease enter valid choice\n");
}
} while (choice != 3);
}
void create(int item)
{
struct node *ptr = (struct node *)malloc(sizeof(struct node *));
if (ptr == NULL)
{
printf("\nOVERFLOW\n");
}
else
{
ptr->data = item;
ptr->next = head;
head = ptr;
printf("\nNode inserted\n");
}
}
void traverse()
{
struct node *ptr;
ptr = head;
if (ptr == NULL)
{
printf("Empty list..");
}
else
{
printf("printing values . . . . .\n");
while (ptr != NULL)
{
printf("\n%d", 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
233
Node inserted
1.Append List
2.Traverse
3.Exit
4.Enter your choice?2
printing values . . . . .
233
23