我们必须打印给定索引处链表节点的数据。与数组链表不同,通常没有索引,因此我们必须遍历整个链表并在到达特定位置时打印数据。
假设列表包含节点 29、34、43、56 和 88 以及值索引为 1、2 和 4,则输出将是这些索引为 34、43 和 88 处的节点。
Linked list: 29->34->43->56->88 Input: 1 2 4 Output: 34 43 88
在上面的链表表示中,黄色突出显示的节点是要打印或特定索引上的节点。
这里使用的方法涉及采用一个指针和一个初始化为 1 的计数器变量,每当遍历该节点时该变量就会递增。计数器与键值匹配。当键与计数器值匹配时,指向节点结构的指针将打印节点的数据并递增到下一个节点,依此类推,为我们提供特定键处的节点。
下面的代码显示了给定算法的 c 实现。
START Step 1 -> create node variable of type structure Declare int data Declare pointer of type node using *next Step 2 -> create struct node* intoList(int data) Create newnode using malloc Set newnode->data = data newnode->next = NULL return newnode step 3 -> Declare function void displayList(struct node *catchead) create struct node *temp IF catchead = NULL Print list is empty return End Set temp = catchead Loop While (temp != NULL) print temp->data set temp = temp->next End Step 4 -> Declare Function int search(int key,struct node *head) Set int index Create struct node *newnode Set index = 0 and newnode = head Loop While (newnode != NULL & newnode->data != key) Set index++ Set newnode = newnode->next End return (newnode != NULL) ? index : -1 step 5 -> In Main() create node using struct node* head = intoList(9) call displayList(head) set index = search(24,head) IF (index >= 0) Print index Else Print not found in the list EndIF STOP
#include <stdio.h> #include <stdlib.h> //structure of a node struct node { int data; struct node *next; }; struct node* intoList(int data) { struct node* newnode = (struct node*)malloc(sizeof(struct node)); newnode->data = data; newnode->next = NULL; return newnode; } //funtion to display list void displayList(struct node *catchead) { struct node *temp; if (catchead == NULL) { printf("List is empty.</p><p>"); return; } printf("elements of list are : "); temp = catchead; while (temp != NULL) { printf("%d ", temp->data); temp = temp->next; } printf("</p><p>"); } //function to search element int search(int key,struct node *head) { int index; struct node *newnode; index = 0; newnode = head; while (newnode != NULL && newnode->data != key) { index++; newnode = newnode->next; } return (newnode != NULL) ? index : -1; } int main() { int index; struct node* head = intoList(9); //inserting elements into a list head->next = intoList(76); head->next->next = intoList(13); head->next->next->next = intoList(24); head->next->next->next->next = intoList(55); head->next->next->next->next->next = intoList(109); displayList(head); index = search(24,head); if (index >= 0) printf("%d found at position %d</p><p>", 24, index); else printf("%d not found in the list.</p><p>", 24); index=search(55,head); if (index >= 0) printf("%d found at position %d</p><p>", 55, index); else printf("%d not found in the list.</p><p>", 55); }
如果我们运行上面的程序,将会生成以下输出。
elements of list are : 9 76 13 24 55 109 24 found at position 3 55 found at position 4
以上是在C语言中,打印给定索引处的链表节点的详细内容。更多信息请关注PHP中文网其他相关文章!