算法思想
代码
#include<iostream>
using namespace std;
struct list
{
int val;
list* next;
list(int x):val(x),next(nullptr){}
};
list* insert(list* head,int x) {
list* p = head;
while (p->next)
{
p = p->next;
}
list* t = new list(x);
p->next = t;
return head;
}
void pprint(list* head) {
if (nullptr == head) {
cout << "链表为空;";
return;
}
while(nullptr != head->next) {
cout << head->val << "->";
head = head->next;
}
cout << head->val << endl;
}
//在无头单链表的一个节点前插入一个节点(不能遍历链表)
void ffrontinsert(list* target,list* t) {
list* temp = target->next;
swap(t->val, target->val);
t->next = temp;
target->next = t;
}
//找打最后一个节点
list* last(list* head) {
list* p = head;
while (p->next)
{
p = p -> next;
}
return p;
}
int main() {
list* head = new list(0);
for (int i = 1; i < 5; i++) {
insert(head, i);
}
list* p = last(head);
cout << "初始链表: ";
pprint(head);
cout << "在最后一个节点之前插入-1: ";
list* t = new list(-1);
ffrontinsert(p, t);
pprint(head);
cout << "在第一个节点之前插入-1: ";
list* a = new list(-1);
ffrontinsert(head, a);
pprint(head);
return 0;
}
运行结果
在写测试main的时候,注意我这里new了一个t和a,由于我的大意,将t插入最后一个节点后,又将t插入第一个节点之前,这就会使得运行的时候出现死循环的情况。才恍然大悟我的t都已经插入到链表了,我怎么还能再次插入呢?所以一定不要疏忽需要创建新的节点进行插入