创建
while(cin>>n&&n!=-1)
{
newnode = new node;
newnode->next = NULL;
newnode->v = n;
if (head==NULL)
{
head = newnode;
tail = newnode;
}
else
{
tail->next = newnode;
tail = newnode;
}
}
遍历
void show()
{
node* s = head;
while (s != NULL)
{
printf("%d ", s->v);
s = s->next;
}
}
删除
bool Delete(int i)
{
node* p, *t;
int j;
if (head == NULL)
{
printf("链表为空\n");
return false;
}
if (i == 1)
{
p = head;
head = head->next;
delete[]p;
}
else
{
j = 1;
t = head;
while (t != NULL && j < i - 1)
{
t = t->next;
j += 1;
}
if (t->next == NULL||i<1)
{
printf("越界\n");
}
else
{
p = t->next;
t->next = p->next;
delete[]p;
}
}
return true;
}
插入
void insert(int x, int index)
{
node* newnode = new node;
newnode->next = NULL;
newnode->v = x;
if (index == 1)
{
newnode->next = head;
head = newnode;
}
else
{
int j = 1;
node* t = head;
while (t != NULL && j < index - 1)
{
j++;
t = t->next;
}
if (t == NULL || index < 1)
{
printf("越界\n");
}
else
{
newnode->next = t->next;
t->next = newnode;
}
}
}
完整代码
#include<iostream>
using namespace std;
struct node
{
int v;
struct node* next;
};
node* head=NULL,* tail=NULL;
bool Delete(int i)
{
node* p, *t;
int j;
if (head == NULL)
{
printf("链表为空\n");
return false;
}
if (i == 1)
{
p = head;
head = head->next;
delete[]p;
}
else
{
j = 1;
t = head;
while (t != NULL && j < i - 1)
{
t = t->next;
j += 1;
}
if (t->next == NULL||i<1)
{
printf("越界\n");
}
else
{
p = t->next;
t->next = p->next;
delete[]p;
}
}
return true;
}
void show()
{
node* s = head;
while (s != NULL)
{
printf("%d ", s->v);
s = s->next;
}
}
void insert(int x, int index)
{
node* newnode = new node;
newnode->next = NULL;
newnode->v = x;
if (index == 1)
{
newnode->next = head;
head = newnode;
}
else
{
int j = 1;
node* t = head;
while (t != NULL && j < index - 1)
{
j++;
t = t->next;
}
if (t == NULL || index < 1)
{
printf("越界\n");
}
else
{
newnode->next = t->next;
t->next = newnode;
}
}
}
int main(void)
{
int n;
node* newnode;
while(cin>>n&&n!=-1)
{
newnode = new node;
newnode->next = NULL;
newnode->v = n;
if (head==NULL)
{
head = newnode;
tail = newnode;
}
else
{
tail->next = newnode;
tail = newnode;
}
}
show();
printf("\n");
Delete(5);
show();
printf("\n");
insert(11,5);
show();
printf("\n");
return 0;
}