#include "pch.h"
#include<iostream>
using namespace std;
struct node
{
int data;
node * next;
};
class linkList
{
public:
linkList();
linkList(int a[], int n); //建立有n个元素的单链表
int length(); //得到单链表的长度
int locate(int x); //查找元素为x的下标
int get(int x); //查找下标为x的元素
void insert(int i, int x); //在第i个元素的位置插入x
int Delete(int i); //删除第i个元素
void printList(); //打印线性表,按序号依次遍历
~linkList();
private:
node * first; //头指针
};
//头插法
/*linkList::linkList(int a[], int n)
{
auto first = new node;
first->next = nullptr;
for (int i = 0; i != n; i++) {
auto s = new node;
s->data = a[i];
s->next = first->next;
first->next = s;
}
}*/
void LinkList::Reverse()
{
auto p = first;
auto q = p->next;
Node * r = nullptr;
first->next = nullptr;
while (q)
{
r = q->next;
q->next = p;
p = q;
q = r;
}
first = p;
}
反转链表的时候first指向了第二个结点,但是我觉得没有问题,是我哪里想错了?
linkList::linkList(int a[], int n) {
first = new node;
first->next = NULL;
auto r = first;
for (int i = 0; i < n; i++) {
auto s = new node;
s->data = a[i];
s->next = NULL;
// r是NULL
r->next = s; //把指向头结点的地址赋给下一个结点
r = s; //每插入一个结点都把该结点"当作"头结点
}
}
尾插法改成这样,原来定义一个局部的指针first,不会对类中的私有变量first进行初始化
locate函数中在 p = p->next;后面添加++cnt;计数器自增,不然查询到的数据的下表始终为1