https://blog.csdn.net/liujian20150808/article/details/50640979?locationNum=4&fps=1
LinkList类
//C++形式的链表的插入,遍历输出,链表倒序等操作
#include<iostream>
#include<cstdlib>
using namespace std;
//节点类
struct ListNode {
public:
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
//链表类
class LinkList {
public:
LinkList() {
head = NULL;
}
void insert(ListNode* node, int position);
void output();
void reverse();
private:
ListNode* head;
};
void LinkList::insert(ListNode* node, int position) {
if (head == NULL) {
head = node;
return;
}
if (position == 0) {
node->next = head;
head = node;
return;
}
ListNode* currentNode = head;
int i = 0;
while (currentNode->next != NULL && i < position - 1) {
currentNode = currentNode->next;
i++;
}
if (i == position - 1) {
node->next = currentNode->next;
currentNode->next = node;
}
}
void LinkList::output() {
if (head == NULL) {
return;
}
ListNode* currentNode = head;
while (currentNode != NULL) {
cout << currentNode->val << " ";
currentNode = currentNode->next;
}
cout << endl;
}
void LinkList::reverse() {
if (head == NULL) {
return;
}
ListNode* currentNode = head->next, * nextNode;
head->next = NULL;
while (currentNode != NULL) {
nextNode = currentNode->next;
currentNode->next = head;
head = currentNode;
currentNode = nextNode;
}
}
int main() {
LinkList linkList;
for (int i = 0; i < 10; i++) {
ListNode* node = new ListNode(i);
linkList.insert(node, i);
}
linkList.output();
linkList.reverse();
linkList.output();
return 0;
}
用vector初始化链表
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
vector<int>vec = { 1,2,3,4,5 };
ListNode* head = new ListNode(vec.front());
ListNode* node = head;
for (int i = 1; i < vec.size(); i++)
{
node->next = new ListNode(vec[i]);
node = node->next;
}
//for (int i = 0; i < vec.size(); i++)
//{
// cout << head->val << ' ';
// head = head->next;
//}
node = head;
while (node != NULL)
{
cout << node->val << ' ';
node = node->next;
}