1.2单链表的基本操作

#include <iostream>
using namespace std;
#define OK 1
#define ERROR 0
typedef int ElemType;
typedef int Status;

//单链表的存储结构
typedef struct LNode
{
    ElemType data;
    struct LNode *next;
} LNode,*LinkList;

//初始化
Status InitList(LinkList &L)
{
    L=new LNode;
    L->next=NULL;
    return OK;
}
//销毁
Status DestroyList(LinkList &L)
{
       LinkList p;
       while(L)
        {
            p=L;
            L=L->next;
            delete p;
        }
       return OK;
 }
//清空
Status ClearList(LinkList L)
{// 将L重置为空表
   LinkList p,q;
   p=L->next;   //p指向第一个结点
   while(p)       //没到表尾
       {q=p->next; delete p; p=q;}
   L->next=NULL;   //头结点指针域为空
   return OK;
 }
//求长度
int  ListLength(LinkList L)
{  //返回L中数据元素个数
    LinkList p=L->next; //p指向第一个结点
    int count=0;
    while(p){//遍历单链表,统计结点数
        ++count;
        p=p->next;
    }
    return count;
 }
//判断是否为空
bool ListEmpty(LinkList L)
{//若L为空表,则返回true,否则返回false
   if(L->next==NULL)
       return true;
   else
       return false;
 }
//取值
Status GetElem(LinkList L,int i,ElemType &e)
{
    LinkList p=L->next;
    int j=1;
    while(p&&j<i)
    {
        p=p->next;
        ++j;
    }
    if(!p||j>i) return ERROR;
    e=p->data;
    return OK;
}
//按值查找
LNode *LocateElem(LinkList L,ElemType e)
{
    LinkList p=L->next;
    while(p &&p->data!=e)
        p->next;
    return p;
}
//插入
Status ListInsert(LinkList &L,int i,ElemType e)
{
    LinkList p=L;
    int j=0;
    while(p && (j<i-1))
    {
        p=p->next;
        ++j;
    }
    if(!p||j>i-1) return ERROR;
    LinkList s=new LNode;
    s->data=e;
    s->next=p->next;
    p->next=s;
    return OK;
}
//删除
Status ListDelete(LinkList &L,int i)
{
    LinkList p=L;
    int j=0;
    while((p->next)&&(j<i-1))
    {
        p=p->next;
        ++j;
    }
    if(!(p->next)||(j>i-1)) return ERROR;
    LinkList q=p->next;
    p->next=q->next;
    delete q;
    return OK;
}
//前插法创建单链表
void CreateList_H(LinkList &L,int n)
{
    L=new LNode;
    L->next=NULL;
    for(int i=0; i<n; ++i)
    {
        LinkList p=new LNode;
        cin>>p->data;
        p->next=L->next;
        L->next=p;
    }
}
//后插法创建单链表
void CreateList_R(LinkList &L,int n)
{
    L=new LNode;
    L->next=NULL;
    LinkList r=L;
    for(int i=0; i<n; ++i)
    {
        LinkList p=new LNode;
        cin>>p->data;
        p->next=NULL;
        r->next=p;
        r=p;
    }
}
//查找哪个元素的前驱
Status ListPrior(LinkList L,ElemType cur_e,ElemType *pre_e)
{
	LinkList q=L->next;//第一个结点
	if(!q)//若链表为空
	    return ERROR;
	LinkList p=q->next;//第二个结点
	while(p)
	{
		if(p->data==cur_e)
		{
			*pre_e=q->data;
			return OK;
		}
		else
		{
			q=p;
			p=p->next;
		}
	}
    return ERROR;
}
//查找哪个元素的后继
Status ListNext(LinkList L,ElemType cur_e,ElemType *next_e)
{
	LinkList p=L->next;
	while(p)
	{
		if(p->data==cur_e&&p->next)
		{
			*next_e=p->next->data;
			return OK;
		}
		else
		    p=p->next;
	}
	return ERROR;
}
//显示线性表
void DisplayList(LinkList L)
{
    LinkList p=L->next;
    while(p)
    {
        cout<<p->data<<"  ";
        p=p->next;
    }
    cout<<endl;
    return;
}
void show_help()
{
    cout<<"******* Data Structure ******"<<endl;
    cout<<"1----清空线性表"<<endl;
    cout<<"2----判断线性表是否为空"<<endl;
    cout<<"3----求线性表长度"<<endl;
    cout<<"4----获取线性表指定位置元素"<<endl;
    cout<<"5----求前驱"<<endl;
    cout<<"6----求后继"<<endl;
    cout<<"7----在线性表指定位置插入元素"<<endl;
    cout<<"8----删除线性表指定位置元素"<<endl;
    cout<<"9----显示线性表"<<endl;
    cout<<"     退出,输入0"<<endl;

}
int main()
{
    char operate_code;
    show_help();
    LinkList L;
    InitList(L);
    ElemType e;
    int i,n;
    printf("请输入链表的个数\n");
    scanf("%d",&n);
    CreateList_H(L,n); 
    while(1)
    {
        cout<<"请输入操作代码:";
        cin>>operate_code;
        if(operate_code=='1')
        {
            cout<<"The list has been cleared."<<endl;
            ClearList(L);//调用操作函数

        }
        else if (operate_code=='2')
        {
            if(ListEmpty(L))
                cout<<"The list is empty."<<endl;
            else
                cout<<"The list is not empty."<<endl;

        }
        else if (operate_code=='3')
        {
            cout<<"The length of list is:"<<ListLength(L)<<endl;

        }
        else if (operate_code=='4')
        {
            cout<<"请输入指定的位置:"<<endl;
            cin>>i;
            if(GetElem(L,i,e) == 1) cout<<"这个位置的数据是:"<<e<<endl;
            else cout <<"error"<<endl;
        }
        else if (operate_code=='5')
        {
            int n;
            cout<<"请输入你想查找哪个元素的前驱:"<<endl;
            cin>>n;
            if(ListPrior(L,n,&e) == 1) cout<<n<<"的前驱为:"<<e<<endl;
                else cout<<"error"<<endl;
        }
        else if (operate_code=='6')
        {
            int n;
            cout<<"请输入你想查找哪个元素的后继:"<<endl;
            cin>>n;
            if(ListNext(L,n,&e)==1) cout<<n<<"的后继为:"<<e<<endl;
                else cout<<"error"<<endl;
        }
        else if (operate_code=='7')
        {
            cout<<"请输入插入元素及其位置:"<<endl;
            cin>>e>>i;
            if(ListInsert(L,i,e)==ERROR) cout<<"您的输入不合法"<<endl;

        }
        else if (operate_code=='8')
        {
            cout<<"请输入你想要删除哪个位置的元素:"<<endl;
            cin>>i;
            if(ListDelete(L,i)==ERROR)  cout<<"error"<<endl;

        }
        else if (operate_code=='9')
        {
            cout<<"The contents of the list are:"<<endl;
            DisplayList(L);

        }
        else if (operate_code=='0')
        {
            break;
        }
        else
        {
            cout<<"\n操作码错误!!!"<<endl;
            show_help();
        }
    }
    //调用销毁线性表函数,如Destroy_List(L);
    DestroyList(L);
    return 0;
}

### 链表基本操作的实现 #### 前插法建立链表 前插法是在每次创建新节点时将其插入到链表头部之前的位置。这种方法使得最近添加的数据位于最前面。 ```c void createListFront(Node **head, int data) { Node *newNode = (Node *)malloc(sizeof(Node)); newNode->data = data; newNode->next = (*head); (*head) = newNode; // 更新头指针指向新的首元结点 } ``` 此函数通过分配内存给一个新的节点并初始化其成员变量来工作[^1]。 #### 后插法建立链表 后插法则相反,它总是把新元素附加在当前列表的最后一项之后。 ```c void createListRear(Node **tail, int data){ Node *newNode = (Node*) malloc(sizeof(Node)); newNode->data = data; newNode->next = NULL; if(*tail == NULL){ *tail = newNode; (*tail)->next = *tail; // 形成环形结构 }else{ Node* temp=*tail; while(temp->next != *tail) temp=temp->next; temp->next=newNode; newNode->next= *tail; *tail=newNode; } } ``` 上述代码展示了如何构建循环单链表,并保持`*tail`始终指向最新的尾部节点[^2]。 #### 按值查找节点 为了找到具有特定值的第一个匹配项: ```c Node* findValue(Node *head, int target){ Node *current = head; do { if(current->data == target) return current; current=current->next; }while(current!=head); return NULL; // 如果未发现目标则返回NULL } ``` 这段程序遍历整个链条直到遇到相同数值为止;如果找不到,则最终会回到起点处退出循环。 #### 按位置查找节点 要定位指定索引处的对象可以这样做: ```c Node* findByPosition(Node *head,unsigned pos){ unsigned count=0; Node *temp=head; if(pos==0 || !head)//处理特殊情况:当pos为零或为空表时直接返回头指针 return head; do{ ++count; if(count==pos) break; temp=temp->next; }while(temp && temp->next!=head); return ((count==pos)?temp:NULL); } ``` 这里实现了对于任意有效下标的访问逻辑,同时也考虑到了边界条件下的异常情况处理。 #### 插入操作 无论是基于位置还是依据关键字来进行插入动作都涉及到相似的过程—即先确定待插入之处再执行实际链接变更. ##### 按位置插入 ```c bool insertByPos(Node **head,int value,unsigned index){ Node *prev=findByPosition((*head),index-1); if(!prev&&index>0)return false;//越界检测 Node *newnode=(Node*)malloc(sizeof(Node)); newnode->data=value; newnode->next=((index<=0)?(*head):prev->next); if(index<=0){ prev=newnode; while(prev->next!=(*head)) prev=prev->next; prev->next=newnode; (*head)=newnode; } else { prev->next=newnode; } return true; } ``` 该算法首先调用了findByPosition()辅助功能获取前一节点的信息以便于后续连接调整. ##### 按值插入 ```c bool insertAfterValue(Node **head, int oldValue, int newValue){ Node *target = findValue(*head,oldValue); if(target==NULL)return false; Node *newNode =(Node*)malloc(sizeof(Node)); newNode ->data =newValue ; newNode ->next=target->next ; target->next=newNode ; return true; } ``` 这个版本接受两个参数分别代表旧键名和希望追加的新条目内容. #### 删除操作 同样地,移除也可以按照两种方式完成 —— 或者是指定序号上的项目被清除掉或者是满足一定属性特征的目标对象遭到剔除。 ##### 按位置删除 ```c bool deleteByIndex(Node **head,unsigned idx){ if(idx==0){//特殊情形:删除第一个元素 Node *toDel=*head; if(toDel->next==toDel){ free(toDel ); *head=NULL; return true; } Node *last=*head; while(last->next!=*head) last=last->next; *head=(*head )->next ; last->next=*head; free(toDel ); return true; } Node *pre=findByPosition(*head,idx-1); if(pre==NULL||!pre->next )return false; Node *toBeDeleted=pre->next ; pre->next=toBeDeleted->next ; free(toBeDeleted ); return true; } ``` 此处特别注意了对首个单元格单独作出安排以适应可能存在的自引用特性. ##### 按值删除 ```c bool removeByKey(Node **head ,int key ){ Node *curr,*prev; curr=*head ; bool isFirst=true; do{ if(curr->data==key){ if(isFirst){ Node *tmp=*head ; if(tmp->next==tmp){ free(tmp ); *head=NULL; return true; } while(tmp->next!=*head ) tmp=tmp->next ; *head=(*head )->next ; tmp->next=*head ; free(curr ); curr=*head ; continue; } prev->next=curr->next ; free(curr ); curr=prev->next ; }else{ prev=curr ; curr=curr->next ; isFirst=false; } }while(curr!=*head ); return curr!=NULL; } ``` 以上就是关于在一个简单的双向闭合型单向链表中实施增删查改四种核心行为的具体编码实例.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值