单链表的基本操作,包括链表初始化、链表创建、插入节点、在指定位置插入节点、删除指定位置节点、打印链表、求链表长度等。
#include<iostream>
#include<stdlib.h>
using namespace std;
struct ListNode
{
int data;
ListNode* next;
};
//链表初始化,头节点为空
ListNode* InitList()
{
ListNode *head;
head=(ListNode*)malloc(sizeof(ListNode));
if(NULL==head)
{
cout<<"no"<<endl;
return NULL;
}
head->next=NULL;
return head;
}
//前向插入链表
void InsertList(ListNode* head)
{
ListNode *p1,*p2;
int key;
cout<<"input a row of number,end with -1:"<<endl;
cin>>key;
while(key!=-1)
{
p1=head->next;
p2=(ListNode*)malloc(sizeof(ListNode));
p2->data=key;
p2->next=p1;
head->next=p2;
cin>>key;
}
}
//后向插入单个数值
void InsertListToTail(ListNode* head,int key)
{
ListNode *p1,*p2;
p1=head;
while(p1->next!=NULL)
{
p1=p1->next;
}
p2=(ListNode*)malloc(sizeof(ListNode));
p2->data=key;
p2->next=NULL;
p1->next=p2;
}
//后向插入多数值
void InsertListTail(ListNode* head)
{
int key;
cout<<"输入要插入的数据,以-1结束:"<<endl;
cin>>key;
while(-1!=key)
{
InsertListToTail(head,key);
cin>>key;
}
}
//创建链表,头节点为空
ListNode* CreateList(ListNode *head)
{
ListNode *p1,*p2;
head=(ListNode*)malloc(sizeof(ListNode));
head->next=NULL;
int key;
cout<<"input a row of number,end with -1:"<<endl;
cin>>key;
while(-1!=key)
{
p1=head->next;
p2=(ListNode*)malloc(sizeof(ListNode));
p2->data=key;
p2->next=p1;
head->next=p2;
cin>>key;
}
return head;
}
//打印链表,头节点为空不打印
void print(ListNode* node)
{
ListNode *p;
p=node->next;
while(p!=NULL)
{
cout<<p->data<<endl;
p=p->next;
}
}
//链表长度
int Length(ListNode* head)
{
ListNode* p;
int i=0;
p=head;
while(p!=NULL)
{
++i;
p=p->next;
}
return i;
}
//找到第i个节点数值,头结点表示0
void findNode(ListNode* head,int i)
{
ListNode* p;
p=head;
if(i>Length(head)-1)
cout<<"超出链表长度范围"<<endl;
else
{
if(i==0)
{
cout<<head->data<<endl;
}
else
{
for(int k=0;k<i;k++)
{
p=p->next;
}
cout<<p->data<<endl;
}
}
}
//在位置i处插入新节点,头结点用0表示
void InsertLocal(ListNode* head,int i,int value)
{
ListNode* p=head,*p2;
p2=(ListNode*)malloc(sizeof(ListNode));
p2->data=value;
p2->next=NULL;
if(i>Length(head))
cout<<"超出链表长度范围"<<endl;
else
{
if(i==0)
{
p2->next=p->next;
p->next=p2;
}
else
if(i==Length(head))
{
while(p->next!=NULL)
{
p=p->next;
}
p->next=p2;
}
else
{
for(int k=0;k<i-1;k++)
{
p=p->next;
}
p2->next=p->next;
p->next=p2;
}
}
}
//删除第i个节点
void deleteNode(ListNode* head,int i)
{
ListNode* p1=head,*p2;
p2=(ListNode*)malloc(sizeof(ListNode));
if(i>Length(head)-1 || i<=0)
cout<<"错误位置"<<endl;
else
{
if(i==Length(head)-1)
{
while(p1->next->next!=NULL)
{
p1=p1->next;
}
p1->next=NULL;
}
else
{
for(int k=0;k<i-1;k++)
{
p1=p1->next;
}
p2=p1->next;
p1->next=p2->next;
}
}
}
int main()
{
struct ListNode *head=NULL;
int i=0,value=0;
head=CreateList(head);
print(head);
return 0;
}
部分细节可能考虑的不周全,仅作参考。