【问题标题】:Printing a string in reverse using a linked list使用链表反向打印字符串
【发布时间】:2015-10-22 00:40:43
【问题描述】:

我构建了一个程序,它从命令行获取一个字符串并使用链表反向打印它。

我目前正在调试我的程序,但我完全卡住了。我有一种感觉,大多数与记忆有关。

/*

Takes a string from the command line.  
Makes a linked-list out of it in reverse order.  
Traverse it to construct a string in reverse.  
Clean up (release memory).
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct st_CharNode 
{
char theChar;
struct st_CharNode *next;
} CharNode;


void reverseIt( char *stringbuffer );


int main( int argc, char *argv[] )
{
char *stringBuffer;

//  Check number of user supplied arguments.  
if( argc != 2 )
{
    fprintf( stderr, "usage: %s string.  This reverses the string "
             "given on the command line\n" );
    exit( -1 );
}

// Copy the argument so we can make changes to it
stringBuffer = malloc( strlen(argv[1]) );
strcpy( argv[1], stringBuffer );

// Reverse the string
reverseIt( stringBuffer );

// Print the reversed string
printf( "the reversed string is '%s'\n", *stringBuffer );

return 0;
}


// Build a linked list backwards, then traverse it.

void reverseIt( char *stringbuffer )
{
CharNode *head, *node;
char *scan, *stop;

// initialize local vars
head = node = NULL;

// find the start and end of the string so we can walk it
scan = stringbuffer;
stop = stringbuffer + strlen(stringbuffer) + 1;

// walk the string
while (scan < stop)
{
    if (head == NULL)
    {
        head = malloc( sizeof(CharNode*) );
        head->theChar = *scan;
        head->next = NULL;
    }
    else
    {
        node = malloc( sizeof(CharNode*) );
        node->theChar = *scan;
        node->next = head;
        head = node;
    }
    scan++;
}

// Re-point to the buffer so we can drop the characters
scan = stringbuffer;

//  Traverse the nodes and add them to the string
while( head != NULL )
{
    *scan = head->theChar;
    free( head );
    node = head->next;
    head = node;
    scan++;
}
// Release head
free( head );   
}

【问题讨论】:

  • “我完全被卡住了”。这不是对问题的充分描述。请说明输入、预期行为、实际行为、您为自己调试所做的工作以及您的具体问题是什么(“为我调试”不是一个具体问题)。
  • 只提到标题:为什么有人会那样?从结尾到开头遍历字符串,并将字符复制到新分配的相同大小的缓冲区。我见过很多对链表概念的“滥用”,但这似乎是“最好的”之一。
  • 你可以只使用链表作为栈。创建新元素时,将其 next 指针设置为第一个元素结构,然后将第一个元素指针设置为新元素结构。用户停止输入后,您只需从第一个指针开始遍历列表,因为它现在已经被审核了。
  • @LászlóKardinál 确实如此,但我仍然想知道:为什么要使用链表?应用浪费资源?
  • 当您需要设计更高级的数据结构时,了解链表会很有用。你可能不会在你的生活中实现任何其他链表,因为会有现成的库,但是当你遇到类似的问题时,你将需要这些结构的逻辑。

标签: c list debugging data-structures


【解决方案1】:

我看到的一个错误是你正在使用这样的 strcpy:

strcpy( argv[1], stringBuffer );

将stringBuffer的值复制到argv[1],你应该反过来做,像这样:

strcpy( stringBuffer, argv[1]);

更多信息请参见 strcpy 的手册页:http://linux.die.net/man/3/strcpy

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-18
    • 1970-01-01
    • 2013-12-17
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    • 2014-02-17
    • 2021-12-18
    相关资源
    最近更新 更多