【发布时间】:2016-10-20 11:20:58
【问题描述】:
我在删除链表中具有指定字符的节点时遇到问题。该程序接受命令行参数,将它们组合在一个字符串中,并将每个字符作为节点添加到链表中。
当我尝试使用命令行参数“mango”删除字符“a”时,它工作正常......即它成功删除了第二个节点。当我尝试用“橙色”做同样的事情时,程序不会删除它......意味着程序不能与第三个和更远的节点一起工作..
该程序不得使用任何全局变量,因此我使用了双指针。 所有功能都正常工作这个问题可能是由于 locate() 和 deleteChar() 函数中的一些错误而发生的,但我无法弄清楚错误是什么。这个问题可以用双指针解决吗?? 我无法弄清楚这个程序有什么问题..我是c编程新手,请帮助我..请纠正我.. 提前谢谢..
代码如下:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct linkedList {
char ch;
struct linkedList *node;
};
char* combineWithNoSpaces(int, char *[]);
void addTolinkedList(char *, struct linkedList **, int *);
void displayWithNoSpaces(struct linkedList **);
struct linkedList *locate(struct linkedList**);
void deleteChar(struct linkedList**);
int main(int argc, char *argv[]) {
/*some variables*/
char *str;
struct linkedList *s;
int indexer = 0;
/*add data from arguments to linked list combine arguments with no spaces
* as a single string
*/
s = (struct linkedList *) malloc(sizeof(struct linkedList));
str = combineWithNoSpaces(argc, argv);
addTolinkedList(str, &s, &indexer);
/*diaplay the added data to linked list with no spaces */
printf("your combined argument is \n");
displayWithNoSpaces(&s);
printf("\n");
/* Delete specified character */
printf("Now Deleting the node with specified character : \n");
deleteChar(&s);
/* Display the data after deleting */
printf("Displaying after deleting..\n");
displayWithNoSpaces(&s);
printf("\n");
return 0;
}
int i = 0;
struct linkedList *locate(struct linkedList **s){
if((*s)->node->ch == 'a'){
return *s;
}
else if((*s)->node!=NULL){
locate(&((*s)->node));
}
return NULL;
}
void deleteChar(struct linkedList **s){
struct linkedList *temp, *tag;
tag = locate(s);
if(tag!= NULL){
temp = tag->node->node;
free(tag->node);
tag->node = temp;
}
}
void displayWithNoSpaces(struct linkedList **s) {
if ((*s) != NULL) {
printf("%c", (*s)->ch);
displayWithNoSpaces(&(*s)->node);
}
return;
}
void addTolinkedList(char *str, struct linkedList **s, int *indexer) {
if (*indexer == strlen(str)) {
*s = NULL;
return;
} else {
(*s)->ch = *(str + *indexer);
(*s)->node = (struct linkedList *) malloc(sizeof(struct linkedList));
++*indexer;
addTolinkedList(str, &(*s)->node, indexer);
}
}
char * combineWithNoSpaces(int argc, char *argv[]) {
int i, j;
int count = 0;
int memory = 0;
char *str;
for (i = 1; i < argc; i++) {
for (j = 0; j < strlen(argv[i]); j++) {
++memory;
}
}
str = (char *) malloc(memory * sizeof(char));
for (i = 1; i < argc; i++) {
for (j = 0; j < strlen(argv[i]); j++) {
*(str + count) = argv[i][j];
++count;
}
}
return str;
}
【问题讨论】:
-
相信我,它不是重复的 progy_rock,函数 locate() 没有正确返回结构指针,或者我不能以正确的方式接受返回的结构指针..除了它处理双指针..我是没有从任何来源获得任何帮助..
-
为什么要递归定位?
标签: c gcc data-structures linked-list singly-linked-list