单向链表(单链表)是链表的一种,其特点是链表的链接方向是单向的,对链表的访问要通过顺序读取从头部开始。
c++代码:
#include<iostream>
#include<stdio.h>
#include<malloc.h>
using namespace std;
typedef struct node
{
int data;
struct node *next;
}node;
//创建
void create(node *head);
//删除某节点
void del(node *head,const int &p);
//取第i个
int getnum(node *head,const int &p);
//在第i个后加一个节点
void insert(node *head,const int &p,const int &x);
//逆置
void revert(node *head);
//打印
void printnode(node *head);
int
main(void)
{
node *head;
head = (node *)malloc(sizeof(node));
head->next = NULL;
create(head);
printnode(head);
revert(head);
printnode(head);
del(head,3);
printnode(head);
printf("%d\n",getnum(head,2));
insert(head,3,6);
printnode(head);
return 0;
}
void create(node *head)
{
//尾插法
node *p,*q;
q = head;
int tmp;
while(~scanf("%d",&tmp) && tmp!=-1)
{
p = (node*)malloc(sizeof(node));
p->data = tmp;
p->next = NULL;
q->next = p;
q = q->next;
}
}
void printnode(node *head)
{
node *q;
for(q=head->next;q!=NULL;q=q->next)
{
printf("%d ",q->data);
}
printf("\n");
}
void del(node *head,const int &p)
{
node *q,*pre;
q = head->next;
if(head==NULL || q==NULL)
return;
int i=0;
while(q && i<p)
{
pre = q;
q = q->next;
i++;
}
pre->next = q->next;
free(q);
}
int getnum(node *head,const int &p)
{
node *q;
q = head->next;
if(head==NULL || q==NULL)
return -1;
int i=0;
while(q)
{
if(i==p)
return q->data;
i++;
q = q->next;
}
}
void insert(node *head,const int &p,const int &x)
{
node *q;
q = head->next;
if(head==NULL || q==NULL)
return;
int i=0;
while(q)
{
if(i==p)
{
node *tmp;
tmp = (node *)malloc(sizeof(node));
tmp->data = x;
tmp->next = q->next;
q->next = tmp;
return;
}
q = q->next;
i++;
}
}
//core
void revert(node *head)
{
node *p1,*p2,*p3,*p4;
p4 = p1 = head->next;
if(head==NULL || p1==NULL)
return;
p2 = p1->next;
while(p2)
{
p3 = p2->next;
p2->next = p1;
p1 = p2;
p2 = p3;
}
p4->next = NULL;
head->next = p1;
}
本文介绍了一种使用C++实现单向链表的基本操作,包括创建、删除节点、获取指定位置的数值、插入节点及链表逆置等功能,并提供了完整的代码示例。


715

被折叠的 条评论
为什么被折叠?



