#include <iostream>
#include "ac.h"
int main(int argc, char** argv) {
Node *head;
while(1){
printf("1.创建链表\n");
printf("2.插入结点\n");
printf("3.删除结点\n");
printf("4.输出链表\n");
printf("5.退出程序\n");
int q = 0;
scanf("%d",&q);
switch(q){
case 1:{
head = creatlist();
printf("请输入你需要创建的链表结点数:");
int num = 0 ;
scanf("%d",&num);
Node *sq = head;
printf("请依次输入结点的值(以空格相隔):");
for(int i = 0 ; i < num ; i ++){
Element n = 0;
scanf("%d",&n);
while(sq->next != NULL) sq = sq->next;
creatNode(sq,n);
}
break;
}
case 2:{
printf("请输入你要插入结点的位置:");
int num;
scanf("%d",&num);
Element e;
printf("请输入你要插入的节点的值:");
scanf("%d",&e);
insert(head,num,e);
break;
}
case 3:{
printf("请输入你要删除结点的位置:");
int num;
scanf("%d",&num);
deleteNode(head,num);
break;
}
case 4:{
print(head);
break;
}
case 5:{
return 0;
break;
}
}
}
return 0;
}
#include<iostream>
#include<malloc.h>
using namespace std;
typedef int Element;
typedef struct Node
{
Node *pre;
Element data;
Node *next;
}Node;
Node *creatlist();
void creatNode(Node *head,Element data);
void insert(Node *head, int e,Element data);
void deleteNode(Node *head ,int e);
void print(Node *head);
#include "ac.h"
Node *creatlist()
{
Node *head = (Node*)malloc(sizeof(Node));
head->next = NULL;
head->pre = NULL;
return head;
}
void creatNode(Node *head,Element data)
{
Node *q = (Node*)malloc(sizeof(Node));
q->data = data;
q->next = head->next;
head->next = q;
q->pre = head;
}
void insert(Node *head, int e,Element data)
{
Node *q = head;
int cn = 0;
while(q->next != NULL && cn < e){
q = q->next;
cn++;
}
if(q->next == NULL &&cn != e){
printf("该位置不合法\n");
return;
}
creatNode(q->pre,data);
}
void deleteNode(Node *head ,int e)
{
Node *q = head;
int cn = 0;
while(q->next != NULL && cn < e){
q = q->next;
cn++;
}
if(q->next == NULL &&cn != e){
printf("该位置不合法\n");
return;
}
q->next->pre = q->pre;
q->pre->next = q->next;
free(q);
}
void print(Node *head)
{
Node *q = head;
if(q->next == NULL){
printf("链表为空\n");
return;
}
while(q->next != NULL){
printf("%d ",q->next->data);
q = q->next;
}
printf("\n");
}
|