私はlinkedlist要素のペアワイズスワップを実行しようとしています。ペアワイズLinkedListのデータをスワップしないノードのスワップ
入力1:1->2->3->4->5
出力1:2->1->4->3->5
入力2:1->2->3->4->5->6
出力2:2->1->4->3->6->5
#include <iostream>
using namespace std;
struct node{
int data;
struct node *next;
};
struct node* func(struct node *f, struct node *s){
if(s==NULL){
return f;
}
struct node *rest1;
rest1 = s->next;
s->next = f;
if(rest1){
f->next = func(rest1,rest1->next);
}
return s;
}
void show(struct node *head){
while(head!=NULL){
cout<<" "<<head->data;
head = head->next;
}
}
int main() {
//code
struct node *head =(struct node*)malloc(sizeof(struct node));
head->data=1;
head->next = (struct node*)malloc(sizeof(struct node));
head->next->data = 2;
head->next->next = (struct node*)malloc(sizeof(struct node));
head->next->next->data = 3;
head->next->next->next = (struct node*)malloc(sizeof(struct node));
head->next->next->next->data = 4;
//head->next->next->next->next=(struct node*)malloc(sizeof(struct node));
//head->next->next->next->next->data=5;
head = func(head,head->next);
show(head);
return 0;
}
データによって要素を交換する代わりに、私はリンクを交換することによって、それらを交換しています
このコードは奇数長のリストでは問題ありませんが、偶数の長さでは機能しません。 私は問題はであると思う:私は作るために使用しています
if(s==NULL){
return f;
}
文の前のf->next=NULL
(偶数長の場合)。
のようになります。おかげで助けを求めて私は別の疑問を持っている。 if(rest1){..}文を削除して、単にf-> next = func(rest1、rest1-> next)のままにしておきます。次の再帰では、f-> nextはNULLになります。つまり、(s == NULL)がNULLのfを返します。私はこれを試しましたが、これは再び動作しません。なぜ説明できますか? – BigA
これは、rest1がnullであるためです。 rest1が指すノードは存在しないので、rest1-> nextは存在しません。 –
このことを私に助けてくれてありがとう – BigA