C链接列表:将节点插入到末尾

时间:2014-12-01 08:41:55

标签: c++ matrix linked-list

我在将代码实现为链接列表方面遇到了麻烦,并希望能够深入了解我的代码。我正在从一个文件中读取打印出两个稀疏矩阵(甚至是两边)来存储为链表。我得到的输出就好像矩阵都是1的,例如

Matrix 1: 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1

输出应该是:

Matrix 1: 1 2 3 4 5

如果来自这样的矩阵:

0 1 0 0 
2 0 0 3 
0 0 0 0
0 0 4 5

我觉得这是我的AddNodes函数的一个问题,但我不确定。

struct Node{
    int row;
    int column;
    int value;
    Node *next;
};

Node *A, *B;

void ReadMatrix(Node *& listpointer, char * file_name);
void AddNode(Node *& listpointer, int row, int col, int nvalue);
//void PrintLL(Node *& listpointer);
//void AddMatrices(Node *& A, Node *& B, int row, int column);
//void PrintMatrix(Node *& listpointer);

int main(){
    A = NULL;
    B = NULL;
    ReadMatrix(A, (char*)"matrix1.txt");
    ReadMatrix(A, (char*)"matrix2.txt");
    PrintLL(A);
    PrintMatrix(A); //etc
}

启动链接列表。

void ReadMatrix(Node *& listpointer, char * file_name){
   //reads a matrix from a file
   int col = 0, row = 0, value = 0; 

   FILE *input = NULL;
   input = fopen(file_name, "r");

   if(input == NULL){
   printf("Cannot open file %s. Exiting.\n", file_name);
   exit(0);
   }
   //reads the matrix dimensions from the first line 
   fscanf(input, "%d %d", &row, &col); 
    printf("%d %d\n", row, col);
   //read matrix 
   for(int i = 0; i < row; i++){
       for(int j = 0; j < col; j++){
       //reads each value from this row (second line onwards)
       fscanf(input, "%d", &value);
       if(value == 0) continue;
       //Include your own add_node(a, i, j, value); function here
       AddNode(listpointer, i, j, value);
       //The next line is for debbuging, it can be commented later
       printf("Element at (%d %d) is different than zero and it is: %d\n",i,j,value);
       }
   }
   fclose(input);
}

添加节点功能。

void AddNode(Node *& listpointer, int row, int col, int nvalue){
   Node * temp;
   temp = new Node;
   temp->row = row;
   temp->column = col;
   temp->value = nvalue;
   temp->next = listpointer;
   listpointer = temp;
   if(listpointer->next == NULL){
       listpointer->next = temp;
   }else{
      Node * current = listpointer;
      while (true){
          if(current->next == NULL){
              current->next = temp;
              break;
          }
      }
   }
   temp->next = NULL;
   return(0);
}

1 个答案:

答案 0 :(得分:2)

AddNote太复杂,包含无限循环。首先,我建议使用std :: list。可以使用push_back方法将元素添加到列表的末尾。然后,如果您确实需要拥有自己的列表实现,则可以选择以下几种方法:

  1. 不仅要记住列表的开头,还要记住最后一个节点。在这种情况下,添加到最后将很简单。
  2. 或者您可以在开头添加新元素,然后在添加所有元素后显示列表。