使用两个链接列表作为函数的参数

时间:2017-01-26 18:26:05

标签: c++ list

我正在尝试比较两个链表,我想创建一个函数,将列表作为参数并进行比较。我将发布该功能。

修改:此功能无效,欢迎任何更正。

#include <cstdio>
#include <iostream>
#include <cstdlib>
using namespace std;

class queue {
private:

    struct node {
        int data;
        node* next;
    };

    typedef struct node* nodeptr;

    nodeptr head;
    nodeptr curr;
    nodeptr temp;

public: // this is where the functions go
    queue();
    bool empty();
    void enqueue(int x);
    void printL();
};

queue::queue() {
    head = NULL;
    curr = NULL;
    temp = NULL;
}

bool queue::empty() {
    bool check = false;
    if (head == NULL) check = true;
    return check;
}

void queue::enqueue(int x) {
    nodeptr n = new node;
    n->next = NULL;
    n->data = x;

    if (head != NULL) {
        curr = head;
        while (curr->next != NULL)   curr = curr->next;
        curr->next = n;
    }
    else  head = n;
}

void queue::printL() {
    curr = head;
    while (curr->next != NULL) {
        printf("%d ", curr->data);
        curr = curr->next;
    }
    printf("\n");
}

bool check(*thetikoi, *arnitikoi) {
    nodeptr a = head.thetikoi;
    nodeptr b = head.arnitikoi;
    while (a != NULL && b != NULL)
        if (thetikoi->data != (arnitikoi->data))
            return false;

    a = a->next;
    b = b->next;
    return (a == NULL && b = NULL);
}

int main() {
    queue thetikoi;
    queue arnitikoi;
    int r = 0;
    while (r != EOF) {
        scanf("%d", &r);

        if (r >= 0) thetikoi.enqueue(r);
        else arnitikoi.enqueue(r);

    }

    thetikoi.printL();
    arnitikoi.printL();

    return 0;
}

1 个答案:

答案 0 :(得分:0)

您的支票功能有几个问题。

在参数列表中,您需要指定参数的类型。

从这个: bool check( *thetikoi , *arnitikoi)

对此:bool check(queue *thetikoi ,queue *arnitikoi)

将本地变量分配给头部指针时,你会有倒退的事情:

此:

 nodeptr a=head.thetikoi;
 nodeptr b=head.arnitikoi;

需要这样:

 nodeptr a=thetikoi->head; // cannot use '.' when accessing fields with a pointer
 nodeptr b=arnitikoi->head;

您也指望首先不是nullptr的两个列表。如果你确定它们是好的,那么不检查就好了。

您的while循环未能附上应在其范围内的所有语句。

  while (a !=NULL && b != NULL )
  if (a->data != (b->data))
   return false;

 a=a->next;
 b=b->next;

应该是:

  while (a !=nullptr && b != nullptr )
  {
      if (thetikoi->data != (arnitikoi->data))
          return false;

      a=a->next;
      b=b->next;
  }