我正致力于实现双向链表。我希望链表受到一定程度的限制。当列表变长时,删除最后一个节点。我在这里有一些问题。我想定义尾部,以便我不必搜索结束。这是我正在处理它的实现将允许长度为4然后开始删除最后一个节点。
/* Doubly Linked List implementation */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct Node {
char command[1024];
struct Node* next;
struct Node* prev;
};
struct Node* head; //global pointing to head
struct Node* tail; //global pointing to tail
//Creates a new Node and returns pointer to it.
struct Node* GetNewNode(char *line) {
struct Node* newCommand = (struct Node*)malloc(sizeof(struct Node));
int i = 0;
while(line[i] != '\0'){
newCommand->command[i] = line[i];
i++;
}
newCommand->prev = NULL;
newCommand->next = NULL;
return newCommand;
}
//Inserts a Node at head of doubly linked list
void InsertAtHead(char *line) {
struct Node* newCommand = GetNewNode(line);
if(head == NULL) {
head = newCommand;
tail = newCommand;
return;
}
head->prev = newCommand;
newCommand->next = head;
head = newCommand;
}
//Use tail to delete the last node
void deleteLast(){
struct Node* temp = tail;
tail = temp->prev;
free(tail->next);
tail->next = NULL;
}
//Print in reverse orer
void Print() {
struct Node* temp = tail;
while(temp != NULL) {
printf("%s \n",temp->command);
temp = temp->prev;
}
}
int main() {
int numNodes = 0;
char line[1024];
head = NULL;
tail = NULL; // empty list. set head/tail as NULL.
printf("next node: ");
while (fgets(line, 1024, stdin)) {
line[strlen(line)-1] = '\0';
if(numNodes == 4){
numNodes -= 1;
deleteLast();
}
InsertAtHead(line);Print();
numNodes += 1;
printf("next node: ");
}
Print();
}
似乎是删除了最后一个节点,但之后打印了一些奇怪的符号。我猜它是一个问题我如何免费()但我无法弄明白。 请注意,此代码中的一部分来自https://gist.github.com/mycodeschool/7429492
答案 0 :(得分:0)
您的代码看起来很好,但是,将命令复制到节点时出错:
while(line[i] != '\0'){
newCommand->command[i] = line[i];
i++;
}
应该是:
while(line[i] != '\0'){
newCommand->command[i] = line[i];
i++;
}
newCommand->command[i] = '\0';
(您忘记终止复制的命令。)
另请注意,您必须检查是否超出可用空间,例如:
while(i<1023 && line[i] != '\0'){
newCommand->command[i] = line[i];
i++;
}
newCommand->command[i] = '\0';