我正在尝试迭代一个向量并将数据放入链表节点......我知道我可以使用STL迭代器来处理向量,但是我可以使用什么来遍历链表?我不认为我可以使用STL列表迭代器,对吗?
List.h
class List {
public:
List();
void addNode(int addData);
void deleteNode(int delData);
void printList();
private:
typedef struct Node {
int data;
Node* next;
}* nodePtr;
nodePtr head;
nodePtr curr;
nodePtr temp;
};
List.cpp
List::List() {
head = NULL;
curr = NULL;
temp = NULL;
}
void List::addNode(int addData){
nodePtr n = new Node;
n->next = NULL;
n->data = addData;
if(head != NULL) {
curr = head;
while (curr->next != NULL) {
curr = curr->next;
}
curr->next = n;
}
else {
head = n;
}
}
void List::deleteNode(int delData) {
nodePtr delPtr = NULL;
temp = head;
curr = head;
while(curr != NULL && curr->data != delData) {
temp = curr;
curr = curr->next;
}
if(curr == NULL) {
cout << delData << " was not in the list.\n";
delete delPtr;
}
else {
delPtr = curr;
curr = curr->next;
temp->next = curr;
if(delPtr == head) {
head = head->next;
temp = NULL;
}
delete delPtr;
}
}
void List::printList() {
curr = head;
while(curr !=NULL) {
cout << curr->data << endl;
curr= curr->next;
}
}
的main.cpp
#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <iterator>
int main(int argc, char** argv) {
cout << "Enter some integers, space delimited:\n";
string someString;
getline(cin, someString);
istringstream stringStream( someString );
vector<int> integers;
int n;
while (stringStream >> n)
List listOfInts;
listOfInts.addNode(/* stuff in here*/)
integers.push_back(n);
return 0;
}
答案 0 :(得分:3)
您无需遍历链接列表。使用addNode
将项目添加到链接列表。
vector<int> vec;
...
List list;
for (vector<int>::iterator i = vec.begin(); i != vec.end() ++i)
list.addNode(*i);
这就是它的全部内容。