根据下面博客学习的:
https://blog.csdn.net/Poxiao2017/article/details/80445145
https://blog.csdn.net/qq_41028985/article/details/82859199
#include "stdafx.h"
#include "iostream"
using namespace std;
/* 单链表 */
typedef struct _LinkList{
_LinkList(){ ; }
int val;
struct _LinkList *next;
}LinkList;
// 头插法初始化链表
LinkList* Creat_Head()
{
LinkList *head, *node;
int num;
head = new LinkList;
head->next = NULL;
cout << "请输入,以0结束" << endl;
cin >> num;
while(num != 0)
{
node = new LinkList;
node->val = num;
node->next = head->next;
head ->next = node;
cin >> num;
}
return head;
}
//尾插法初始化链表
LinkList* Cread_End()
{
LinkList *head, *node, *end;
int num;
head = new LinkList;
head->next = NULL;
end = head;
cout << "请输入,以0结束" << endl;
cin >> num;
while (num != 0)
{
node = new LinkList;
node->val = num;
end->next = node;
end = node;
cin >> num;
}
end->next = NULL; // 尾指针
return head;
}
// 指定位置插入链表
void Insert(LinkList *first, LinkList *second, int n)
{
int num = 0;
LinkList *p = second;
while((first->next != NULL) && (num < n)){
first = first->next;
num++;
}
while(second->next != NULL){
second = second->next;
}
if(num == n){
second->next = first->next;
first->next = p->next;
}
}
// 遍历链表
void Print_LinkList(LinkList *List)
{
LinkList *node = List -> next;
while (node != NULL)
{
cout << "list=" << node->val << "\n";
node = node->next;
}
}
// 获取链表结点个数
int Get_LinkList_Size(LinkList *List)
{
int size = 0;
LinkList *node = List->next;
while (node != NULL){
size++;
node = node->next;
}
cout << "list结点个数为" << size << "\n";
return size;
}
// 删除指定位置的节点
void Del_LinkList_val(LinkList *List, int n)
{
int num = 0;
int size = Get_LinkList_Size(List);
LinkList *end;
// 删除的位置大于或等于结点的个数,直接删除最后一个结点
if(size <= n)
{
while ((List->next != NULL) && (num < n-1)){
List = List->next;
num++;
}
end = List->next;
List->next = NULL;
free(end);
}
else
{
while ((List->next != NULL) && (num < n)){
List = List->next;
num++;
}
if (n == num)
{
end = List->next;
List->next = end->next;
free(end);
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
LinkList *list1 = Creat_Head();
//LinkList *list2 = Cread_End();
//Insert(list1, list2, 2);
//Print_LinkList(list1);
Del_LinkList_val(list1, 2);
Print_LinkList(list1);
return 0;
}