#include<iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
typedef struct LNode{
int data;
struct LNode *next;
}LNode,*LinkList;
LinkList InitList(LinkList &L)
{
// It have the head list and the head node is null,so we can use it without restrict
L=new LNode;
L->next=NULL;
return L;
}
//LinkList InitList(LinkList &L)
//{
// // It haven't head list and the head node is null,so we can use it without restrict
// L=new LNode;
// L->data=1;
// L->next=NULL;
// return L;
//}
LinkList ListTailInsert(LinkList &L,int x){
LNode *s1 = new LNode;
LinkList s2=L;
while(s2->next)
{
s2=s2->next;
}
s1->data = x;
s1->next=s2->next;
s2->next=s1;
return L;
}
LinkList ListHeadInsert(LinkList &L,int x)
{
LNode *s1 = new LNode;
s1->data=x;
s1->next=L->next;
L->next=s1;
return L;
}
LNode *GetElem(LinkList L,int x)
{
int j=1;
LNode *p =L->next;
if(x==0)
return p;
if(x<1)
return NULL;
while(p&&j<x)
{
p=p->next;
j++;
}
return(p);
}
LNode* LocateElem(LinkList L,int e){
LNode *p = L;
while(p)
{
if(p->data==e)
{
return p;
}
p=p->next;
}
return NULL;
}
LinkList Find_Tail_Insert(LinkList &L,LNode *node,int x)
{
LNode *p;
//p is the LNode of i-1
p=GetElem(L,x-1);
node->next=p->next;
p->next=node;
// p is HeadInsert that is reverse i-1 and i
// int temp=p->data;
// p->data=node->data;
// node->data=temp;
return L;
}
LinkList ListDelete(LinkList &L,int x)
{
LNode *p,*q;
p=GetElem(L,x-1);
q=p->next;
p->next=q->next;
//free the memory
free(q);
return L;
}
int Length(LinkList L)
{
int x=0;
LinkList p=L->next;
while(p)
{
x++;
p=p->next;
}
return x;
}
void PrintList(LinkList L){
LinkList s=L->next;
while(s)
{
if(s->next==NULL)
printf("%d",s->data);
else
printf("%d\n",s->data);
s=s->next;
}
return ;
}
int main()
{
int x;
LNode *y = new LNode;
y->data=999;
y->next=NULL;
LinkList L;
L=InitList(L);
L=ListHeadInsert(L,1);
L=ListHeadInsert(L,2);
L=ListHeadInsert(L,3);
L=ListHeadInsert(L,4);
// cout<<Length(L); output length of list
// ListDelete(L,2);//delete node in the List
// Find_Tail_Insert(L,y,3); // find out the site and interposition
//
// y=LocateElem(L,2); //chase down node in the list
// cout<<y->data;
// cout<<GetElem(L,2);
// L=ListTailInsert(L,1);
// L=ListTailInsert(L,2);
// L=ListTailInsert(L,3);
// L=ListTailInsert(L,4);
PrintList(L);
}
数据结构链表的增删查改(带头结点)
最新推荐文章于 2024-07-17 23:54:01 发布