Cプログラムで余分なスペースや変更を加えずに、リンクリストの裏面を印刷します。
タスクは、余分なスペースを使用せずにリンクリストの最後からノードを印刷することです。つまり、余分な変数はなく、最初のノードを指すヘッドポインターが移動します。
例
Input: 10 21 33 42 89 Output: 89 42 33 21 10
再帰的アプローチ(余分なスペースを使用)、リンクリストの反転(指定されたリンクリストの変更が必要)、スタック上の要素のプッシュ、要素のポップと表示など、リンクリストを逆の順序で印刷するソリューションは多数あります。 1つずつ(スペースO(n)が必要)、これらのソリューションはO(1)よりも多くのスペースを使用しているようです。
O(1)を超えて使用せずに結果を達成するには、次のことができます-
- リンクリスト内のノードの数を数えます
- i =nから1にループし、i番目の場所のノードを出力します。
アルゴリズム
START Step 1 -> create node variable of type structure Declare int data Declare pointer of type node using *next Step 2 ->Declare function int get(struct node* head) Declare variable as int count=0 Declare struct node *newme=head Loop While newme!=NULL Increment count by 1 Set newme = newme->next End Return count Step 3 -> Declare Function void push(node** headref, char newdata) Allocate memory using malloc Set newnode->data = newdata Set newnode->next = (*headref) Set (*headref) = newnode Step 4 -> Declare function int getN(struct node* head, int n) Declare struct node* cur = head Loop for int i=0 and i<n-1 && cur != NULL and i++ Set cur=cur->next End Return cur->dataStep 5 -> Declare function void reverse(node *head) Declare int n = get(head) Loop For int i=n and i>=1 and i— Print getN(head,i) End Step 6 ->In Main() Create list using node* head = NULL Insert elements through push(&head, 89) Call reverse(head) STOP
例
#include<stdio.h>
#include<stdlib.h>
//node structure
struct node {
int data;
struct node* next;
};
void push(struct node** headref, int newdata) {
struct node* newnode = (struct node*) malloc(sizeof(struct node));
newnode->data = newdata;
newnode->next = (*headref);
(*headref) = newnode;
}
int get(struct node* head) {
int count = 0;
struct node* newme = head;
while (newme != NULL){
count++;
newme = newme->next;
}
return count;
}
int getN(struct node* head, int n) {
struct node* cur = head;
for (int i=0; i<n-1 && cur != NULL; i++)
cur = cur->next;
return cur->data;
}
void reverse(node *head) {
int n = get(head);
for (int i=n; i>=1; i--)
printf("%d ", getN(head, i));
}
int main() {
struct node* head = NULL; //create a first node
push(&head, 89); //pushing element in the list
push(&head, 42);
push(&head, 33);
push(&head, 21);
push(&head, 10);
reverse(head); //calling reverse function
return 0;
} 出力
上記のプログラムを実行すると、次の出力が生成されます
89 42 33 21 10
-
実際にC言語で反転せずに、リンクリストの反転を印刷します
タスクは、再帰関数を使用して、指定されたリンクリストの逆を印刷することです。プログラムは逆に印刷する必要がありますが、リストを逆にしないでください。つまり、ノードの順序は同じままです。 ここで、プログラムは、リストの最後のノードに格納されているNULLが調べられ、ヘッドノードのデータが出力されるまで、最初のノードのアドレスを含むヘッドポインタを次のノードに移動します。 例 Input: 29 34 43 56 Output: 56 43 34 29 まず、ノードがリストに挿入され、挿入されたノードを指すポインターが開始されます。最終リストが作成された後、一時ポインタが最初のノードポイ
-
配列の左回転をCプログラムのO(n)時間とO(1)空間で出力します。
いくつかのサイズnと複数の整数値の配列が与えられているので、与えられたインデックスkから配列を回転させる必要があります。 -のようなインデックスkから配列を回転させたい 例 Input: arr[] = {1, 2, 3, 4, 5} K1 = 1 K2 = 3 K3 = 6 Output: 2 3 4 5 1 4 5 1 2 3 2 3 4 5 1 アルゴリズム START Step 1 -> Declare functio