[英]Doubly linked list delete last C
我正在研究双向链表的实现。 我希望链表受某些长度限制。 当列表变长时,请删除最后一个节点。 我在这里有一些问题。 我想定义尾巴,这样我就不必搜索结尾了。 这是我正在努力的实现,它将允许长度为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();
}
它似乎正在删除最后一个节点,但之后打印一些奇怪的符号。 我猜测这与我的free()问题有关,但我无法弄清楚。 注意其中一些代码来自https://gist.github.com/mycodeschool/7429492
但是,您的代码看起来不错,但是将命令复制到节点时出错:
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';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.