在使用此功能来反向链接列表时,为什么不能使用所示代码反向链接?

时间:2018-09-26 19:10:58

标签: c linked-list reverse singly-linked-list

有人可以解释下面的代码,尤其是循环中的代码吗? 我想为什么我无法将Next->next指向current来连接节点。

void reverse(){
    Node *reverse = head;
    Node *prev = NULL, *Next, *current;
    current = reverse;

    while(current != NULL){
        Next = current->next; 
        current->next = prev;
        Next->next = current;
    }
    head = current;
}

1 个答案:

答案 0 :(得分:0)

为什么不使用二进制搜索树? Wich基本上就像是双向链表,我将为您提供我的代码,并乐于学习:

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

struct Structure
{
  int n;
};

struct StructureNode
{
  struct Structure structure;
  struct StructureNode * next;
  struct StructureNode *prev;
};

typedef struct StructureNode * Node;


void bst(struct Structure data, Node * p )
{
Node pp = *p;
  if(pp == NULL)
  {
    pp = (Node)malloc(sizeof(struct StructureNode));
    pp->next = NULL;
    pp->prev = NULL;
    pp->structure = data;
    *p = pp;
  }
  else if(data.n == pp->structure.n )
    {
      return;
    }
  else  if(data.n > pp->structure.n )
    {
      bst(data, &pp->next);
    }
  else
    {
      bst(data, &pp->prev);
    }

  }

void Read(struct Structure * p, Node list)
{
  printf("\nOne Integer Number:");
  scanf(" %d", &p->n);
}


void View(Node node)
{
    while(node != NULL)
    {
      printf("[ %d ]\n", node->structure.n);
      node = node->next;
    }

}
void displayDesc(Node p)
{
  if(p != NULL)
  {

  displayDesc(p->next);
  printf("\n[ %d  ]\n", p->structure.n);
  displayDesc(p->prev);

  }
}

void displayAsc(Node p)
{
  if(p != NULL)
  {

  displayAsc(p->prev);
  printf("\n[  %d  ]\n", p->structure.n);
  displayAsc(p->next);

  }
}

int Menu()
{
  int c;
  printf("\n****list.c by St3veR0nix*****\n"
        "\n1) Insert a number in the Tree\n"
        "\n2) Display in Ascending Order \n"
        "\n3) Display in Descending Order\n");
  scanf(" %d", &c);

  return c;
}

int main()
{
Node list = NULL;
struct Structure structure;
int c;
do
{
 c  = Menu();
 switch (c)
 {
   case 1:   Read(&structure, list);
             bst(structure, &list);

             break;
   case 2:
             displayAsc(list);
             break;

   case 3:   displayDesc(list);
             break;
   default:  c = 0;
 }

} while (c != 0);

return 0;
}