完善上一篇的单链表
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
using namespace std;
struct node
{
int data;
struct node* next;
};
struct node* head;
struct node* Createlink(struct node* head,int n) {
head = (struct node*)malloc(sizeof(struct node));
head->next = NULL;
struct node* tail = head;
while (n-->0)
{
struct node* p= (struct node*)malloc(sizeof(struct node));
cin >> p->data;
p->next = NULL;
tail->next = p;
tail = p;
}
return head;
}
void Print(struct node* head) {
struct node* p = head;
p = p->next;
while (p!=NULL)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
void h_insert(struct node* head) {
struct node* p = (struct node*)malloc(sizeof(struct node));
cin >> p->data;
struct node* temp = head->next;
head->next = p;
p->next = temp;
}
void t_insert(struct node* head) {
struct node* p = head;
while (p->next!=NULL)
{
p = p->next;
}
struct node* temp = (struct node*)malloc(sizeof(struct node));
cin >> temp->data;
temp->next = NULL;
p->next = temp;
}
void h_delete(struct node* head) {
struct node* temp = head->next;
head->next = temp->next;
free(temp);
}
void t_delete(struct node* head) {
struct node* p = head;
struct node* temp = head;
while (p->next != NULL)
{
temp = p;
p = p->next;
}
temp->next = NULL;
free(p);
}
void index_delete(struct node* head,int x) {
struct node *p, *q;
p = head;
while (p->next!=NULL)
{
q = p->next;
if (q->data == x) {
p->next = q->next;
free(q);
q->next = NULL;
continue;
}
p = p->next;
}
}
void index_insert(struct node* head,int index)
{
int i = 0;
struct node* p = head;
while (p != NULL && i < index)
{
p = p->next;
i++;
}
if (p==NULL||i>index)
{
cout<<"数组越界"<<endl;
return;
}
struct node* q = (struct node*)malloc(sizeof(struct node));
cin >> q->data;
struct node* temp = p->next;
p->next = q;
q->next = temp;
}
int main() {
int n;
cin >> n;
head=Createlink(head, n);
index_insert(head,2);
Print(head);
system("pause");
return 0;
}