2013-06-29 43 views
0

我有一个链表包括像这样的字符...插入一个链表到另一个链表

node1 - "p" 
    node2 - "o" 
     node3 - "p" 

我需要一个函数,将采取三种perameters ...

node *replaceChar(node *head, char key, char *str) 

这个函数的规定。 head是列表的头部,'key'和'str'只保证包含字母数字字符(A-Z,a-z和0-9)。 str的范围可以从1到1023个字符(包含)。

所以,如果我调用此函数与这些perameters ..

node *head == /*the head of the list to be examined*/ 

char key == "p" 

char *str == "dog" 

新的名单看起来就像这样......

node1 - 'd' 
    node2 - 'o' 
     node3 - 'g' 
      node4 - 'o' 
       node5 - 'd' 
        node6 - 'o' 
         node7 - 'g' 

“P”的所有实例都以“家的狗'

我有一个toString函数,它接受一个字符串并将其转换为链接列表并返回头部。因此,假设您可以拨打海峡=“狗”的功能,所以...

toString(str) == /*this will return the head to the list made from the str*/ 

如果还不清楚我的问题是什么...我难倒就如何写replaceChar功能一个发生在三个参数..我可以使用字符串创建一个新的列表,并找到所有键的实例,但是使新列表适合旧列表而不丢失指针正在杀死我。

我曾经尝试这样做......

while(head->data != NULL) 
    { 
     if(head->data == key) 
      { 
       node *newListHead = toString(str); 

       head = newListHead; 

       /*here I lose track of the old list*/ 
+2

而你遇到的问题是? –

+0

我在问题主体的最后几行重申了我的问题。 – FunkyT

+0

我不知道... @JoachimPileborg –

回答

0

你可以这样开始:

node *replaceChar(node *head, char key, char *str) 
{ 
    node *cur, prev; 
    for (cur = head, prev = NULL; cur != NULL; prev = cur, cur = cur->next) 
     if (cur->ch == key) { 
      node *hstart = toString(str); 
      for (node *hend = hstart; hend->next != NULL; hend = hend->next) 
       ; 
      if (prev == NULL) 
       head = hstart; 
      else 
       prev->next = hstart; 
      hend->next = cur->next; 
      free(cur); 
     } 

} 

我的假设: 您的节点结构是这样的:

sturct node { 
    char ch; 
    struct node* next; 
}; 

toString(str)作品非常好。