反向双链表

时间:2017-02-15 17:32:09

标签: c list pointers linked-list reverse

我必须编写一个函数来反转双链表,以便尾部成为头部。

例如,之前的元素: {(1,1),(1,2),(2,2),(2,3)}

后:    {(2,3),(2,2),(1,2),(1,1)}

这是结构:

  struct snake {
    unsigned int i;
    unsigned int j;
    struct snake *next;
    struct snake *prev;
  };

这是我必须使用的功能原型:

void snake_reverse(struct snake **s);

我尝试了类似这样的事情以及其他一些尝试

void snake_reverse(struct snake **s) {
struct snake *last, *tmp = NULL;

last = *s;

while (last !=  NULL)
 {
   tmp = last->prev;
   last->prev = last->next;
   last->next = tmp;
   last = last->prev;
 }

 if(tmp != NULL )
    *s = tmp->prev;
}

还试过这个:

while (last !=  NULL)
 {
   tmp = last->next;
   last->next = last->prev;
   last->prev = tmp;
   last = tmp;
 }

 if(tmp != NULL )
    *s = tmp;
但是他不行。我几乎可以肯定我没错。 列表的第一个 - > prev是NULL,列表的最后一个 - >下一个是NULL。

我没有错误或崩溃,但该功能的任务是通过反转所有元素并更改列表的头部来反转蛇的方向。 你能说出这里有什么问题吗?

编辑:问题出在该程序的另一个模块中,而不是由我做的。

无论如何,最好的解决方案是kmkaplan。谢谢大家

3 个答案:

答案 0 :(得分:1)

您必须将*s设置为列表的新头部。这是列表的旧尾部,也就是您处理的最后一个元素。

void snake_reverse(struct snake **s) {
    struct snake *last, *tmp = NULL;
    last = *s;
    while (last !=  NULL) {
        *s = last
        tmp = last->prev;
        last->prev = last->next;
        last->next = tmp;
        last = last->prev;
    }
}

答案 1 :(得分:0)

我不确定,但我认为你的while循环中的最后一行代码是错误的。据我所知,最后一个变量是蛇的尾巴。这意味着last-> next = null。在你的第二行代码中,你在前一个最后一个null的时候,在最后一行代码中,最后一个变为0.我认为在while循环中更改你的最后一行代码会改变这个。

#main {
    color: #fff;
    text-shadow:
     3px 3px 0 #000,
    -1px -1px 0 #000,  
     1px -1px 0 #000,
    -1px 1px 0 #000,
     1px 1px 0 #000;
    left: -200px;
    margin: auto;
    margin-top: auto;
    top: 150px;
    width: auto;
    font-size: 1.5em;
}

ol {
    counter-reset: li;
    list-style-type: none;
}

ol li {
    position:relative;
}

ol li:before {
    content: counter(li)'.';
    counter-increment: li;
    position:absolute;
    right:100%;
    margin-right:10px;
    text-shadow:
      3px 3px 0 #000,
     -1px -1px 0 #000,  
      1px -1px 0 #000,
     -1px 1px 0 #000,
      1px 1px 0 #000;
}

答案 2 :(得分:0)

您永远不会设置列表的新头部,因为在while循环后tmp始终为NULL。试试这个;

void snake_reverse(struct snake **s) {
  struct snake *last, *newHead, *tmp = NULL;

  last = *s;

  while (last !=  NULL)
  {
     tmp = last->prev;
     if (tmp!=NULL)
       newHead = tmp;
     last->prev = last->next;
     last->next = tmp;
     last = last->prev;
  }

  *s = newHead;
}
相关问题