实现头插 并且每次插入后打印已有全部元素
struct Node
{
int date;
Node* next;
};
Node* PNode;
void Insert(int x)
{
Node* temp = new Node();
temp->date = x;
temp->next = NULL;
if (PNode != NULL)
{
temp->next = PNode;
}
PNode = temp;
}
void Print()
{
Node* temp = PNode;
while (temp != NULL)
{
cout << temp->date;
temp = temp->next;
}
cout << endl;
}
int main()
{
PNode = NULL;
int n,x;
cout << "请输入您想要存储的数据个数:" << endl;
cin >> n;
for (int i = 0; i < n; i++)
{
cout << "请输入第" << i+1 << "个数字" << endl;
cin >> x;
Insert(x);
Print();
}
}
实现任意位置插入
void Insert(int x, int n)
{
assert(n >= 0/* && n < GetLength(head)*/);
Node* temp = new Node();
temp->date = x;
temp->next = NULL;
if (n == 1)
{
temp->next = head;
head = temp;
return;
}
else
{
assert(head != NULL);
Node* temp2 = head;
for (int i = 0; i < n -2; i++)
{
temp2 = temp2->next;
}
temp->next = temp2->next;
temp2->next = temp;
}
return;
}
删除指定位置
void Delete(int x)
{
assert(head != NULL);
assert(x >= 0/* && x < GetLength(head)*/);
Node* temp = head;
if (x == 1)
{
head = temp->next;
delete temp;
return;
}
for (int i = 0; i < x - 2; i++)
{
temp = temp->next;
}
Node* temp2 = temp->next;
temp->next = temp2->next;
delete temp2;
}
逆置链表(迭代实现)
void Reverse()
{
Node* prev, *current, *next;
prev = NULL;
current = head;
next = NULL;
while (current != NULL)
{
next = current->next;
current->next = prev;
prev = current;
current = next;
}
head = prev;
}
逆置链表(递归实现)
void Reverse2(Node * p)
{
if (p->next == NULL)
{
head = p;
return;
}
Reverse2(p->next);
Node* q = p->next;
q->next = p;
p->next = NULL;
}
打印链表(递归实现)
void Print2(Node * p)
{
if (p == NULL)
{
cout << endl;
return;
}
cout << p->date;
Print2(p->next);
}