单链表的一些基本操作

好久没看书了,好多东西都忘了,有空复习下链表的一些基本知识.

链表的结构大概是这样的:


下面给出链表的一些基本操作,直接上代码:

// List.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace std;


struct List
{
	double value;
	List* next;
};

//头插法,返回头结点
List* CreateListByHead()
{
	List* head = new List;
	head->next = NULL;	

	int num = 10;
	for (int i = 1;i < num; i++)
	{
		List *l = new List;
		l->value = i;
		l->next = head->next;
		head->next = l;
	}

	return head;
}

//尾插法,返回头结点
List* CreateByTail()
{
	List* head = new List;
	List* tail = head;
	tail->next = NULL;

	int num = 10;
	for (int i = 1; i < num; i++)
	{
		List *l = new List;
		l->value = i;
		l->next = NULL;
		tail->next = l;
		tail = l;
	}
	return head;
}

//打印链表
void PrintList(List* head)
{
	List* l = head->next;
	while (l)
	{
		cout<<l->value<<endl;
		l = l->next;
	}
}

//返回链表长度
int GetLength(List* head)
{
	int len = 0;
	List* l = head->next;
	while (l)
	{
		len++;
		l = l->next;
	}
	return len;
}

//返回对应索引的指针
List* GetPointerByIndex(List*head,int index)
{
	if (GetLength(head) >= index)
	{
		int n = 1;
		List* l = head->next;
		while (l)
		{
			if (n == index)
			{
				break;
			}
			l = l->next;
			n++;
		}
		return l;
	}
	else
	{
		cout<<"非法获取"<<endl;
		return NULL;
	}
}


void InsertListNode(double value,int position,List* head)
{
	if (position > GetLength(head))
	{
		cout<<"非法插入"<<endl;
		return;
	}
	List* l = GetPointerByIndex(head,position);
	if (l)
	{
		List* node = new List;
		node->value = value;
		node->next = l->next;
		l->next = node;
	}
}

void DelListNode(List* head,int position)
{
	if (position > 0 && position <= GetLength(head))
	{
		List* nowNode   = GetPointerByIndex(head,position);
		if (position > 1)
		{
			List* frontNode = GetPointerByIndex(head,position - 1);
			frontNode->next = nowNode->next;
			nowNode = NULL;
		} 
		else //删除第一个节点
		{
			head->next = nowNode->next;
			nowNode = NULL;
		}
		
	} 
	else
	{
		cout<<"非法删除"<<endl;
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	//List* head = CreateListByHead();
	List* head = CreateByTail();
	InsertListNode(10,8,head);
	DelListNode(head,7);
	PrintList(head);
	cout<<"链表长度为 "<<GetLength(head)<<endl;
	//cout<<GetPointerByIndex(head,8)->value;
	system("pause");
	return 0;
}
最后的结果如下:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值