以下失誤可能察覺,但只有迄今爲止獲得的主要功能運行
new_sequence
不Sequence
它創建初始化什麼。 lst
當你訪問它在sequence_insert_at
struct node* temp = s->lst;
這裏應該怎麼看起來像
Sequence new_sequence()
{
Sequence s = malloc(sizeof(struct sequence));
if(!s)
{
printf("Out of memory. Can't allocate s\n");
exit(EXIT_FAILURE);
}
s->lst = malloc(sizeof(struct node));
if(! s->lst) {
printf("Out of memory. Can't allocate lst\n");
}
s->lst->rest = NULL;
s->length = 0;
return s;
}
也s->lst->rest
必須被設置爲NULL
沒有初始化,這就是告訴用戶列表中有沒有更多的元素一個不是end
女巫變得過時了。
struct sequence
{
struct node* lst;
int length;
};
您應該將序列本身傳遞給您的函數,而不是指向序列中某些內部數據的指針。
add_to_front(&temp, item);
你sequence_insert_at
功能應該是可以處理任何位置上的一個不add_to_front()
所以很容易從add_to_front()
與位置0
打電話和你具有孔的工作在一個函數中完成的,而不是一個半在這裏和那裏有一半。
void sequence_insert_at(Sequence s, int pos, int item)
{
if(s && pos <= s->length) {
print_sequence(s);
struct node *newnode = malloc(sizeof(struct node));
if (newnode == NULL) {
printf("ERROR! add_to_front ran out of memory!\n");
exit(EXIT_FAILURE);
}
newnode->first = item;
struct node* temp = s->lst;
struct node* prv = NULL;
for(int i = 0; i < pos; i++) {
printf("skip %d\n", temp->first);
prv = temp;
temp = temp->rest;
}
newnode->rest = temp;
if(pos == 0) {
printf("insert as first\n");
s->lst = newnode;
} else {
printf("insert before %d\n", temp->first);
prv->rest = newnode;
}
++s->length;
}
}
和add_to_front
需要
void add_to_front(Sequence s, int item) {
sequence_insert_at(s, 0, item);
}
因爲只有一個語句在列表
void add_to_back(Sequence s, int item) {
sequence_insert_at(s, s->length, item);
}
一個小測試與主體功能
void print_sequence(Sequence s)
{
struct node* temp = s->lst;
for(int i = 0; i < s->length; temp = temp->rest) {
printf("%d ", temp->first);
i++;
}
printf("\n");
}
int main()
{
Sequence derp = new_sequence();
sequence_insert_at(derp, 0, 14);
add_to_front(derp, 16);
sequence_insert_at(derp, 0, 17);
sequence_insert_at(derp, 2, 15);
add_to_back(derp, 13);
print_sequence(derp);
delete_sequence(derp);
return 0;
}
後面插入
輸出是:
17 16 15 14 13
你必須通過其他功能並修復它們。
最後我要指出,你已經選擇變量名是有點混亂,如果不是誤導,我會說出他們這樣
typedef struct node {
int data; /* the data that a node holds */
struct node* next; /* the pointer to the next node */
} Node_t;
typedef struct sequence {
struct node* head; /* head or first element of the sequence/list */
int length; /* length is ok but size is better */
} Sequence_t;
如何'add_to_front'樣子? – A4L 2013-03-07 18:46:04
這是在ideone鏈接。 – 2013-03-07 18:46:33