- 用三个指针来实现
s:用来建立新的链表
p:找到下一个要放在头部的结点
l:存放上一个结点的地址
- 传节点的时候不能传insertBefore(m2, m2->next, n),像这种传节点+节点后继节点的方式,改链的时候会发生错误,具体例子如下代码
#include <iostream>
#include <stdlib.h>
#include <list>
using namespace std;
typedef struct Linklist {
int data;
struct Linklist *next;
}*Lnode, Linklist;
Lnode insertBefore(Lnode &f, Lnode &p, Lnode &s) {
Lnode x = f;
if (f != p) {
while ((x->next != p) && (x->next != NULL)) {
x = x->next;
}
x->next = s;
s->next = p;
}
else {
s->next = p;
f = s;
}
return f;
}
int main() {
Lnode s, m1, m2;
s = (Lnode)malloc(sizeof(Lnode));
m1 = s;
m2 = s;
for (int i = 1; i < 5; i++) {
s->data = i;
s->next = (Lnode)malloc(sizeof(Lnode));
s = s->next;
}
s->data = 5;
s->next = NULL;
Lnode n = (Lnode)malloc(sizeof(Lnode));
n->data = 100;
Lnode m22 = m2->next;
m2 = insertBefore(m2, m22, n);
for (int i = 1; i < 7; i++) {
cout << m2->data << endl;
m2 = m2->next;
}
system("pause");
return 0;
}