|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
//list.h
#include<iostream>
#include<assert.h>
#include<windows.h>
using namespace std;
//结构体
struct listNode
{
int data;//data是一个整形变量,用来存放结点中的数据。当然,data可以是任何数据类型,包括结构体类型或类类型。
listNode* next;//尾节点
listNode(int key)
:data(key)
, next(NULL)
{}
};
class linklist
{
typedef listNode Node;
public:
linklist()
:head(NULL)
{}
void pushback(const int key)
{
Node* cur = head;
if (head == NULL)
{
head = new Node(key);
return;
}
while (cur->next)
{
cur = cur->next;
}
cur->next= new Node(key);
}
void print()
{
assert(head != NULL);
Node* cur = head;
while (cur)
{
cout << cur->data << "->";
cur = cur->next;
}
}
Node* _head()
{
return head;
}
Node* end()
{
Node* cur = head;
while (cur->next)
{
cur = cur->next;
}
return cur;
}
void insert(linklist x,int a,int b)
{
const int key=0;
Node *p, *q;//p指向结点a,q指向结点a的前一个结点的next,s指向结点b
Node* m = head;
if (head == NULL)
{
head = new Node(key);
return;
}
while (m->next)
{
m = m->next;
}
m->next = new Node(key);
m->data = b;
p = head;
if (head == NULL)//a为空链表,则将b放在第一个位置
{
head = m;
m->next = NULL;
}
else if (p->data = a)//a为第一个结点
{
m->next = p;
m = head;
}
else
{
while (p->data != a&&p->next != NULL)//找打结点a的前一个结点
{
q = p;
p = p->next;
}
if (p->data == a)//如果有结点a,则将结点b插入到结点a的前面
{
q->next = m;
m->next = p;
}
else//如果没有结点a,则将结点b插到链表的尾部
{
p->next = m;
m->next =NULL;
}
}
}
Node* head;
};
void test()
{
linklist s,q;
s.pushback(1);
s.pushback(2);
s.pushback(3);
s.insert(s,1,4);
s.print();
}
//test.cpp
#include"list.h"
int main()
{
test();
system("pause");
return 0;
}
我想写一个链表插入的函数,利用两个结点参数在s链表的第一个结点处 插入元素4,但是结果是错的,求哪位大神帮忙指点一下,代码很混乱,希望大神帮忙看一下,研究了好久,智商实在压制,菜鸟跪求指点。
你插入的结点m初值是根结点,没有重新申请开辟内存,链表插入的新结点要分配相应的内存空间后用指针指向它后再插入到链表中,仔细看下书或教学视频,我扫了下你的代码没有申请内存的操作
|
|