C語言中列印連結串列中指定索引的節點
我們需要列印給定索引處連結串列節點的資料。與陣列不同,連結串列通常沒有索引,因此我們必須遍歷整個連結串列,並在到達特定位置時列印資料。
假設列表包含節點 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.
");
return;
}
printf("elements of list are : ");
temp = catchead;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
}
printf("
");
}
//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
", 24, index);
else
printf("%d not found in the list.
", 24);
index=search(55,head);
if (index >= 0)
printf("%d found at position %d
", 55, index);
else
printf("%d not found in the list.
", 55);
}輸出
如果執行上述程式,則會生成以下輸出。
elements of list are : 9 76 13 24 55 109 24 found at position 3 55 found at position 4
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP