#include <iostream>
using namespace std;
**//**链表不是随机存取结构,不能直接按序号访问结点。头结点可以看做第0个结点,所以计数器j加到i时为第i个结点。**
typedef struct node
{
int data;
struct node *next;
}ListNode;
**//创建带头结点的单链表**
ListNode * creat_l(int n)
{
ListNode *head;
ListNode *p,*q;
p=(ListNode *)malloc(sizeof(ListNode));
cin>>p->data;
head=p;
for(int i=1;i<n;i++)
{
q=(ListNode *)malloc(sizeof(ListNode));
cin>>q->data;
p->next = q;
p=q;
}
p->next = NULL;
return head;
}
**//输出链表**
void out_l(ListNode *head)
{
ListNode *h = head;
while(h)
{
cout<<h->data<<endl;
h=h->next;
}
}
**//删除第n个结点**
ListNode * erase(int n,ListNode *head)
{
ListNode *h = head;
ListNode *p;
for(int i=0;i<n-1;i++)
{
h=h->next;
}
p=h->next;
h->next = p->next;
return head;
}
**//在第n个位置插入结点**
ListNode * insert(int n,ListNode *head)
{
ListNode *h=head;
ListNode *p;
ListNode *q=(ListNode *)malloc(sizeof(ListNode));
cin>>q->data;
for(int i=0;i<n-1;i++)
{
h=h->next;
}
q->next=h->next;
h->next=q;
return head;
}
int main()
{
int n;
cin>>n;
ListNode *h=creat_l(n);
out_l(h);
cout<<endl;
ListNode *hh=erase(3,h);
out_l(hh);
ListNode *il=insert(3,h);
out_l(il);
return 0;
}
单链表的插入和删除
猜你喜欢
转载自blog.csdn.net/gyhjlauy/article/details/89191811
今日推荐
周排行