单链表

本文介绍了一种使用C++实现单向链表的基本操作,包括创建、删除节点、获取指定位置的数值、插入节点及链表逆置等功能,并提供了完整的代码示例。

单向链表(单链表)是链表的一种,其特点是链表的链接方向是单向的,对链表的访问要通过顺序读取从头部开始。

Link zh.png


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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值