研究生复试要求掌握链表的基本操作,就写了些demo实现了一下。
都是简单的操作,是做链表题的基础。
#include<iostream>
#include<stdio.h>
#include<cstdio>
#include <malloc.h>
using namespace std;
typedef struct LNode{
int data;
struct LNode *next;
}LNode, *LinkList;
int GetElem(LinkList L,int i)
///得到L中第i个位置的节点,带头节点
{
LNode *p;
p = L->next;
int j=1;
while(p&&j<i)
{
p=p->next;
j++;
}
if(!p||j<i){
return false;
}
else{
return p->data;
}
}
LNode *GetElem2(LinkList L,int i)
{
///带头节点
LNode *p=L->next;
int j=1;
if(i==0){
return L;
}
if(i<1)
return NULL;
while(p&&j<i){
p=p->next;
j++;
}
return p;
}
void ListAfterInsert(LNode *L,int i)
{
LNode *p;
p=(LinkList)malloc(sizeof(LNode));
p->data=i;
p->next=NULL;
L->next=p;
}
void ListAfterInsert2(LNode *L,int i,int e)
{
LNode *p=GetElem2(L,i-1);
LNode *s;
s=(LinkList)malloc(sizeof(LNode));
s->data=e;
s->next=p->next;
p->next=s;
}
int ListInsert(LinkList &L,int i,int e)
{
LNode *p;
p=L;
int j=1;
while(p&&j<i-1)
{
p=p->next;
j++;
}
if(!p||j>i-1){
return false;
}
else
{
LNode *s;
s=(LinkList)malloc(sizeof(LNode));
s->data=e;
s->next=p->next;
p->next=s;
return true;
}
}
int DeleteLink(LinkList &L,int i)
{
LNode *p;
LNode *pre;
pre=L;
int countt=0;
p=L;
while(p)
{
if(countt==i)
{
pre->next=p->next;
free(p);
return true;
}
else{
pre=p;
p=p->next;
}
countt++;
}
}
void DeleteLink2(LinkList L,int i)
{
LNode *p=GetElem2(L,i-1);
LNode *q=p->next;
p->next=q->next;
free(q);
}
LinkList CreateLink()
{
LinkList Lhead=new LNode;
LinkList Lpre=Lhead;
LinkList Lpcur=NULL;
Lhead->data=0;
Lhead->next=NULL;
for(int i=1;i<=5;i++)
{
Lpcur=new LNode;
/*
if(Lhead==NULL){
Lpcur->data=i;
Lpcur->next=NULL;
Lhead->data=i;
}
else
{
Lpcur->data=i;
Lpcur->next=NULL;
Lpre->next=Lpcur;
}
*/
Lpcur->data=i;
Lpcur->next=NULL ;
Lpre->next=Lpcur;
Lpre=Lpcur;
}
return Lhead;
}
void Display(LinkList P){
while(P)
{
LinkList q;
q=P;
P=P->next;
cout<<q->data<<" ";
}
cout<<endl;
}
LNode *LocateElem(LinkList L,int e)
///查找定值e返回节点
{
LNode *p =L->next;
while(p!=NULL&&p->data!=e){
p=p->next;
}
return p;
}
int LocateElem2(LinkList L,int e)
{
///查找定值返回位置
int num=1;
LNode *p =L->next;
while(p!=NULL&&p->data!=e){
p=p->next;
num++;
}
return num;
}
int main(){
///1,2,3,4,5
cout<<"hello the world"<<endl;
LNode *L=NULL;
LinkList P=NULL;
//L=(LinkList)malloc(sizeof(LNode));
/*
for(int i=1;i<=5;i++)
{
ListAfterInsert(L,i);
}
*/
/*
L->data=0;
L->next=NULL;
ListAfterInsert(L,1);
ListAfterInsert(L,2);
ListAfterInsert(L,3);
LNode *p=L;*/
P=CreateLink();
ListInsert(P,2,33);
DeleteLink(P,1);
/*
while(P)
{
LinkList q;
q=P;
P=P->next;
cout<<q->data<<endl;
}
*/
cout<<"按值查找Location:"<<endl;
cout<<LocateElem2(P,2)<<endl;
Display(P);
cout<<"按序号查ELEM:"<<endl;
if(GetElem2(P,2)){
LNode *Q=GetElem2(P,2);
cout<<Q->data<<endl;
}
Display(P);
cout<<"DISPLAY"<<endl;
cout<<"在第二个位置插入100:"<<endl;
ListAfterInsert2(P,2,100);
Display(P);
cout<<"删除第i个节点"<<endl;
DeleteLink2(P,5);
Display(P);
//p=L;
//cout<<q<<endl;
/*****
int a=3;
int num[3]={0,2,3};
int *p;
*p=a;
int *q=num;
cout<<*q<<endl;
cout<<q<<endl;
cout<<*p<<endl;
cout<<p<<endl;
***/
}