通过链表实现赋值,插入,删除,输出的功能,没有多余拉扯,不提供注释,希望大家体会链表之美:
头部
#include<iostream>
#include<stdlib.h>
using namespace std;typedef struct node{int data;struct node * next;struct node * prev;
} node;
声明
node* create();
void output(node *head);
void insert(int position, int x, node *head);
void deletee(node *head);
主函数
int main(){node*head=create();cout << "输出结果:" << endl;output(head);int position, x;cin >> position >> x;insert(position, x, head);cout << "输出结果:" << endl;output(head);deletee(head);cout << "输出结果:" << endl;output(head);return 0;
}
赋值
node * create(){node *p, *pre, *head;head = (node *)malloc(sizeof(node));head->next = NULL;pre = head;int x;while(1){cin >> x;if(x==-1)break;p = (node *)malloc(sizeof(node));p->data = x;p->next = NULL;pre->next = p;pre = p;}return head;
}
插入
void insert(int position,int x,node*head)
{int i = 0;node *s= head;while(i<position-1){s = s->next;i++;}if(i>position-1)cout << "beyond" << endl;else{node *l = (node *)malloc(sizeof(node *));l->data = x;l->next = s->next;s->next = l;}
}
删除
void deletee(node*head)
{int position;int i = 0;node *j = head;node *k;cin >> position;while(i<position-1){j = j->next;i++;}j->next = j->next->next;
}
输出
void output(node* head){node *q;q = head->next;while(q!=NULL){cout << q->data << " ";q = q->next;}cout << endl;
}