を引き起こし、私は入力に整数のリストを受け取り、プログラムを書いて、それが次の操作を実行する整数に基づいています:場合リンクリストの要素を削除すると、無限ループ
は、絶対値を削除します数は、リストの末尾にそれを追加し、正であっても、そのリスト
数が正と奇数の場合の上で追加した場合、入力の値が
負である
数値が0の場合は、プログラムを終了してリストを印刷します。
私の問題は、私はリストを印刷するときに、プログラムが無限ループに入り、リスト上の無限ループの原因となるpop_el機能、です。 これは私のコードです:
#include <stdio.h>
#include <stdlib.h>
typedef struct ll_node_S * ll_node_ptr;
struct ll_node_S
{
int v;
ll_node_ptr next;
};
typedef struct ll_node_S ll_node;
ll_node_ptr push_tail(ll_node_ptr head, int v)
{
ll_node_ptr backup = head;
ll_node_ptr current = head;
while(current->next != NULL)
{
current = current->next;
}
current->next = (ll_node_ptr) malloc(sizeof(ll_node));
current->v = v;
return backup;
}
ll_node_ptr push_head(ll_node_ptr head, int v)
{
ll_node_ptr new_head = (ll_node_ptr)malloc(sizeof(ll_node));
new_head->v = v;
new_head->next = head;
return new_head;
}
ll_node_ptr pop_el(ll_node_ptr head, int el)
{
ll_node_ptr backup = head;
ll_node_ptr current = head;
ll_node_ptr previous = NULL;
int found = 0;
while(current != NULL && !found)
{
if(current->v == el)
{
if(previous == NULL)
{
backup = current->next;
free(current);
current = backup;
previous = current;
}
else
{
previous->next = current ->next;
free(current);
current = current->next;
}
found = 1;
}
else
{
previous = current;
current = current->next;
}
}
return backup;
}
void print(ll_node_ptr head)
{
ll_node_ptr current = head;
printf("%d\n", head->v);
while(current->next != NULL)
{
current = current->next;
printf("%d\n", current->v);
}
}
int isPair(int n)
{
return ((n % 2) == 0);
}
int main(int argc, char** argv)
{
int n = 1;
ll_node_ptr list = NULL;
while(n != 0)
{
scanf("%d", &n);
if(n < 0)
{
list = pop_el(list, -n);
}
else
{
if(isPair(n))
{
list = push_head(list, n);
}
else
{
list = push_tail(list, n);
}
}
}
print(list);
//should free the list
return 0;
}
、これは私が反対のコードをテストしてい(入力に渡された)テストケースである:
2
2
9
:以下の出力を生成する必要があり
4
5
2
-4
-5
-3
9
2
0
手がかりはありますか?
を向上させることができます。 –
私はテストケースをcatしてプログラムにパイプするカスタムスクリプトを使用してcloud9環境でプログラムを開発していますので、c9で提供されているデバッグツールを使用できません(AC環境使用時は動作しません) – Crax
効率的に作業したい場合は、ローカルマシン上のいくつかの開発環境に投資する必要があります。そして「投資」によって、私は必ずしも「お金」を意味するのではなく「時間」を意味します。 –