Data Structure - list operation

/ ** 
 * 3/5 2020 
 * list 
 * / 
#include <the iostream> 
the using namespace STD; 
typedef int elemType; 
/ ** 
 * single linked list 
 * / 
typedef struct {LNode 
    elemType Data; 
    LNode * Next; 
} LNode, * the LinkedList; 
/ ** 
 * output list 
 * @param L 
 * / 
void Print (the LinkedList L) { 
    LNode * = L-P> Next; 
    the while (! P = NULL) { 
        COUT p-<<> Data << ""; 
        P = p-> Next; 
    } 
} 
/ ** 
 * interpolation method to establish the first single chain 
 * @param L 
 * @return 
 * / 
the LinkedList List_InsertHead (the LinkedList & L) {  
    LNode * TEMP;
    int Data;
    L=(LNode*)malloc(sizeof(LNode));
    L->next=NULL;
    cin>>data;
    while(data!=9999){
        temp=(LNode*)malloc(sizeof(LNode));
        temp->data=data;
        temp->next=L->next;
        L->next=temp;
        cin>>data;
    }
    return L;
}
/**
 * 尾插法建立链表
 * @param L
 * @return
 */
LinkedList List_TailInsert(LinkedList &L){
    int data;
    L=(LNode*)malloc(sizeof(LNode));
    L->next=NULL;
    LNode *p=L,*q;
    cin>>data;
    while(data!=9999){
        q=(LNode*)malloc(sizeof(LNode));
        q->data=data;
        p->next=q;
        p=q;
        cin>>data;
    }
    p->next=NULL;
    return L;
}
/**
 * 按位序查找
 * @param L
 * @param i
 * @return
 */
LNode *GetElem(LinkedList 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;
}
LNode *LocateElem(LinkedList L,ElemType e){
    LNode *p=L->next;
    while(p&&p->data!=e){
        p=p->next;
    }
    return p;
}
/**
 * 节点插入
 * @param L
 * @param i
 * @param data
 */
void InsertNode(LinkedList L,int i,int data){
    LNode *p=GetElem(L,i-1);
    LNode *temp=(LNode*)malloc(sizeof(LNode));
    temp->data=data;
    temp->next=p->next;
    p->next=temp;
}
/**
 * 节点前插
 * @param L
 * @param i
 * @param data
 */
void InsertNode_Pre(LinkedList L,int i,int data){
    LNode *p=GetElem(L,i);
    LNode *temp=(LNode*)malloc(sizeof(LNode));
    temp->next=p->next;
    p->next=temp;
    temp->data=p->data;
    p->data=data;
}
/**
 * 删除操作
 * @param L
 * @param i
 */
void DeleteLNode(LinkedList L,int i){
    LNode *p=GetElem(L,i-1);
    LNode *q=p->next;
    if(p->next==NULL){
        return;
    }
    p->next=q->next;
    free(q);
}
/**
 * 删除指定节点
 * @param L
 * @param i
 */
void DeleteLNode(LinkedList L,LNode *node){
    LNode *temp=L->next;
    for(;node->data!=temp->data&&node->next!=temp->next;temp=temp->next);
    LNode *p=temp->next;
    int value=node->data;
    node->data=p->data;
    p->data=value;
    node->next=p->next;
    free(p);
}
int main(){
    LinkedList list;
    List_TailInsert(list);
    DeleteLNode(list,GetElem(list,2));
    print(list);
    return 0;
}
Published 17 original articles · won praise 6 · views 560

Guess you like

Origin blog.csdn.net/qq_41037075/article/details/104675206