C ++使用双向链表中的某些值制作列表

时间:2016-11-20 13:37:23

标签: c++ doubly-linked-list

我的双重链接列表存在问题。

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

struct node {
    int value;
    node* next;
    node* prev;
};


void printList(node* head);

void main(int args, char** argv) {
    int x;
    node* head;
    node* tail;
    node* n;

    n = new node;
    n->value = 1;
    n->prev = NULL;
    head = n;
    tail = n;

    cout << "Enter number of elements: ";
    cin >> x;
    for (int i = 0; i < x; i++) {
        cout << "Enter element value: ";
        n = new node;
        cin >> n->value;
        n->prev = tail;
        tail->next = n;
        tail = n;
    }
    tail->next = NULL;


    system("pause");
}


void printList(node* head) {
    node* temp = head;
    while (temp != NULL) {
        cout << temp->value << " ";
        temp = temp->next;
    }
    cout << endl;
}

Q1 - 如何在双向链表中找到第一个负面元素的索引?

Q2 - 如何从双向链表中的所有负面元素创建新列表,然后打印新列表(负面元素)和双向链表(没有负面元素)?

1 个答案:

答案 0 :(得分:0)

这是未经测试的代码,但它应该给你良好的开端。

class LinkedList {
public:
   LinkedList();
   void insertHead(int val) {
     node* n;
     n->value = val;
     n->next = head;
     n->prev = tail;
     head->prev = n;
     head = n;
   }
   void insertTail(int val) {
     node* n;
     n->value = val;
     tail->next = n;
     n->next = head;
     n->prev = tail;
     tail = n;
   }
   LinkedList makeNewList(int i) {
     node* n = head;
     LinkedList *newList = new LinkedList();
     while(n->next != nullptr && n->next != head) {
        if (n->value < i) {
            newList->insertHead(n->value);
        }
        n = n->next;
     }
   }
private:
   node* head = nullptr;
   node* tail = head;
}