发布网友 发布时间:2022-04-23 03:40
共1个回答
热心网友 时间:2023-10-13 15:11
#include <iostream.h>
struct node {
int data;
struct node *next;
};
node *createlist() { /*以上是构造一个链表*/
node *u,*p,*head;
int x;
head = new node;
head->data = 0;
p = head;
while( x != 0 ) {
cout << "请输入数据(0结束输入过程): ";
cin>>x;
if(x == 0) break;
u = new node;
u->data = x;
u->next = NULL;
p->next = u;
p = u;
}
return head;
}
void displist(node *L) {
int i = 0;
node *p = L->next;
while(p != NULL) {
if(i % 10 == 0) cout << endl;
cout << p->data << " ";
p = p->next;
i++;
}
}
int list_length(node *L) { // 求表的长度
int count = 0;
node *p = L->next;
while (p != NULL) {
count++;
p = p->next;
}
return (count);
}
void traversal(node *L) { //输出连表中的值
if(!L) return;
node *p = L->next;
while(p) {
cout << p->data << " ";
p = p->next;
}
}
void list_insert(node *L,int i,int x) { // 在指定位置插入结点
node *s,*p = L->next;
int k = 0;
while((k != i - 1) && (p != NULL)) {
p = p->next;
k++;
}
if(p == NULL) cout << "序号错。" << endl;
else {
s = new node;
s->data = x;
s->next = p->next;
p->next = s;
}
}
void list_delete(node *L,int i) { //删除结点
node *u,*p = L;
int k = 0;
while((k != i - 1) && (p != NULL)) {
p = p->next;
k++;
}
if((p == NULL) || (p->next == NULL)) cout << "删除序号错。" << endl;
else {
u = p->next;
p->next = u->next;
delete u;
}
}
void list_insertincrease( node *L,int x) { // 在增序表中插入结点
node *u,*p = L;
while((p->next != NULL) && (p->next->data < x)) p = p->next;
u = new node;
u->data = x;
u->next = p->next;
p->next = u;
}
void main() {
//int x ,i;
node *head;
head = createlist();
cout<<"显示链表:"<<endl;
displist(head);
cout << "插入数据36后 :" << endl;
list_insert(head,2,36);
displist(head);
cout << "删除结点2后 :" << endl;
list_delete(head,2);
displist(head);
}
追问怎么各种功能都没实现啊 可不是追答你说的几项功能已经全部实现,除了“在一个递增有序的链表L中插入一个值为x的元素,并保持其递增有序特性”外,都已经得到验证,请你仔细看看运行截图!
你可以用循环语句创建一个增序链表,例如
node *head,*p*q;
head = p = new node;
for(int i = 1;i data = 2*i;
p->next = q;
p = q;
}
p->next = NULL;
然后执行函数
void list_insertincrease( node *L,int x) { // 在增序表中插入结点
node *u,*p = L;
while((p->next != NULL) && (p->next->data next;
u = new node;
u->data = x;
u->next = p->next;
p->next = u;
}
即可。