好久没看书了,好多东西都忘了,有空复习下链表的一些基本知识.
链表的结构大概是这样的:
下面给出链表的一些基本操作,直接上代码:
// 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;
}
最后的结果如下: