Basic operations on the linked list structure C implementation (create, insert, delete, reverse, merge, search, whether there is a ring, intersection of the linked list)

Source: Internet
Author: User

Recently, I have been plagued by job hunting. In the technical questions, linked list operations related to data structures account for about half of the list operations. Therefore, I should study the linked list operations and use the relevant code to implement them, if something is wrong, I hope readers can point it out. Thank you very much ~!

A linked list is the most basic data structure. It can be divided into single-chain tables, cyclic Single-Chain tables, double-chain tables, and cyclic double-chain tables. In actual applications, the single linked list is the most widely used and basic structure. Only by learning this simple structure can we better master the complex data structure. The storage structure includes sequential storage and chained storage.

The following describes how to implement the chain storage structure of a single-chain table:

The Code is as follows: (C implementation interface, C ++ test)

Header file: (linklist. h)

/* ===================================================== ========================================================== ================= Copyright (c) 2011 weedge. all rights reserved. @ coder: weedgee-mail: weege@126.com @ Date: 2011/09/12 (happy Mid-Autumn Festival !) @ Comment: the basic operations on a single-chain table structure provide the corresponding interface: 1. create a createlist, insert the insertlistnode node, delete the elistnode node, and print the traverselist.2. non-recursive and recursive implementations of the chain table reverse reservelist and the merge mergelist3. sort the sortlist of the two single-chain tables to find, whether islooplist4 exists in a single-link table. The linked list intersection isintersectlist, and the first node intersectedfirstnode. * ===================================================== ========================================================== =======*/# ifndef link_list_h # define link_list_h # ifdef _ cplusplusextern "C "{# Endifenum status {infeasible =-2, error =-1, false = 0, true = 1, OK = 2}; typedef int elemtype; /* linear table structure */typedef struct node {elemtype data; struct node * Next;} lnode, * linklist; typedef int (* cmpfun) (elemtype A, elemtype B ); typedef void (* printfun) (elemtype ); /* ------------------------ create, destroy, empty linked list, and length of linked list --------------------------- * // * Create a linked list with n elements */INT createlist (linklist * l, int N);/* initial condition: the linear table l already exists. Operation Result: The linear table L */void destroylist (linklist * l) is destroyed./* initial condition: the linear table l already exists. Operation Result: if l is empty, true is returned. Otherwise, false */INT isempty (linklist L) is returned./* initial condition: the linear table l already exists. Operation Result: return the number of data elements in L */INT listlength (linklist L);/* If the I-th element exists, the value is assigned to E and OK is returned, otherwise, Error */INT getelem (linklist L, int I, elemtype * E) is returned./* the bits of the 1st data elements in L that meet the requirements of E and compare () are returned; if such a data element does not exist, the returned value is 0 */INT localeelem (linklist L, elemtype E, cmpfun compare);/* If cur_e is a data element of L, if it is not the first one, pre_e is used to return its precursor and OK is returned. Otherwise, the operation fails and the pre_e is not defined. infeasible */INT priorelem (linklist L, elemtype cur_e, elemtype * pre_e);/* If cur_e is a data element of L and is not the last one, use next_e to return its successor. Return OK; otherwise, the operation fails. next_e is not defined. infeasible */INT nextelem (linklist L, elemtype cur_e, elemtype * next_e) is returned ); /* -------------------------- insert and delete nodes --------------------------- * // * Insert the Element E */INT insertlistnode (linklist * l, int I, elemtype E);/* Delete the I-th element in a single-chain linear table l, and E returns its value */INT deletelistnode (linklist * l, int I, elemtype * E);/* initial condition: the linear table l already exists. Operation Result: Call the visit () function to print */void traverselist (linklist L, printfun visit) for each data element of L in sequence ); /* -------------------------- reverse and merge nodes --------------------------- * // * recursively reverse a single-chain table */void reverselistrecursive (linklist * head ); /* Non-recursive reverse single-chain table */lnode * reverselist (linklist head);/* recursively merge two linked lists */lnode * mergelist_recursive (linklist head1, linklist head2 ); /* Non-recursive merge of two linked lists */lnode * mergelist (linklist head1, linklist head2 ); /* -------------------------- sort and query the linked list ------------------------- * // * perform Bubble Sorting (non-decreasing) on the linked list */void sortlist (linklist * head);/* locate the intermediate node in the linked list, returned by midnod */void findmid (linklist head, lnode ** midnode ); /* -------------------------- a single-link table ------------------------- * // * determines whether the linked list contains a ring */INT islooplist (linklist head ); /* -------------------------- 2 single-chain tables intersection ------------------------- * // * determines whether two non-ring Single-Chain tables are intersection */INT isintersectlist (linklist head1, linklist head2, find the first intersection node */lnode * intersectedfirstnode (linklist head1, linklist head2); # ifdef _ cplusplus} # endif

 


Source File: (linklist. c)

/* ===================================================== ========================================================== ===================== Copyright (c) 2011 weedge. all rights reserved. @ coder: weedgee-mail: weege@126.com @ Date: 2011/09/12 (happy Mid-Autumn Festival !) @ Comment: basic operations on the structure of a single-chain table: 1. create a createlist, insert the insertlistnode node, delete the elistnode node, and print the traverselist.2. non-recursive and recursive implementations of the chain table reverse reservelist and the merge mergelist3. sort the sortlist of the two single-chain tables to find, whether islooplist exists in a single-chain table, 4. linked List intersection isintersectlist, the first node of the intersection, intersectedfirstnode * ================================== ========================================================== ===============*/# include <stdio. h> # include <stdlib. h> # include <assert. h> # include "linkl Ist. H "/* Create a linked list with n elements */INT createlist (linklist * l, int N) {int I; lnode * P, * s; If (n <1) {return false;} * l = (linklist) malloc (sizeof (lnode); P = * l; printf ("Please input % d Data \ n", N ); for (I = 0; I <n; I ++) {S = (lnode *) malloc (sizeof (lnode); scanf ("% d ", & (S-> data);/* insert to the end of the table */p-> next = s; P = s; /* insert to the header * // * s-> next = p-> next; P-> next = s; */} * l = (* l)-> next; /* headless node */S-> next = NULL;/* the pointer field of the last node at the end of the table indicates null */return true ;} /* Initial condition: the linear table l already exists. Operation Result: destroy the linear table L */void destroylist (linklist * l) {linklist Q; while (* l) {q = (* l)-> next; free (* l); * l = Q ;}/ * initial condition: the linear table l already exists. Operation Result: if l is empty, true is returned; otherwise, false */INT isempty (linklist L) {If (L! = NULL)/* non-empty */return false; elsereturn true;}/* initial condition: the linear table l already exists. Operation Result: returns the number of data elements in L */INT listlength (linklist L) {int I = 0; linklist P = L; /* P points to the first node */while (P)/* not to the end of the table */{I ++; P = p-> next;} return I ;} /* If element I exists, the value is assigned to E and OK is returned. Otherwise, Error */INT getelem (linklist L, int I, elemtype * E) is returned) {Int J = 1;/* j is the counter */linklist P = L;/* P points to the first node */while (P & J <I) /* search backward by pointer until P points to the I-th element or P is null */{P = p-> next; j ++ ;} if (P = NULL | j> I)/* the I-th element does not exist */Return Error; * E = p-> data; /* obtain the I-th element */Return OK;}/* initial condition: The linear table l already exists, and compare () is the data element judgment function (0 is satisfied, otherwise 1 is met) * // * operation result: returns the order of the 1st data elements that meet the condition of compare () with E in L. * // * If such a data element does not exist, the returned value is 0 */INT localeelem (linklist L, elemtype E, cmpfun compare) {int I = 0; linklist P = L; while (p) {I ++; If (* compare) (p-> data, e) = 0)/* find such a data element */return I; P = p-> next;} return 0;}/* initial condition: the linear table l already exists * // * operation result: If cur_e is a data element of L, if it is not the first one, pre_e is used to return its precursor. * // * OK is returned. Otherwise, the operation fails. If pre_e is not defined, infeasible */INT priorelem (linklist l, elemtype cur_e, elemtype * pre_e) {linklist Q, P = L;/* P points to the first node */while (p-> next)/* P The specified node has a successor */{q = p-> next;/* Q is a successor of p */if (Q-> DATA = cur_e) {* pre_e = p-> data; Return OK;} p = Q;/* P shifts backward */} return infeasible;}/* initial condition: linear table l already exists * // * operation result: If cur_e is a data element of L and is not the last one, use next_e to return its successor, * // * To Return OK; otherwise, the operation fails. next_e is not defined. infeasible */INT nextelem (linklist L, elemtype cur_e, elemtype * next_e) is returned. {linklist P = L; /* P points to the first node */while (p-> next)/* P indicates that the node has a successor */{If (p-> DATA = cur_e) {* next_e = p-> next-> data; Return OK;} p = p-> next;} re Turn infeasible;}/* Insert the Element E */INT insertlistnode (linklist * l, int I, elemtype e) {Int J = 0 before position I in a single-chain linear table L; linklist P2, P1 = * l, s; If (p1 = NULL | I <1)/* I less than 1 */Return Error; S = (linklist) malloc (sizeof (struct node);/* generate new node */S-> DATA = E; while (P1-> next! = NULL & J <i-1)/* Find the I-1 node */{P2 = p1; P1 = p1-> next; j ++ ;} if (j = 0) {/* Add S */S-> next = * l; * l = s;} before the header ;} else if (null = p1-> next) {/* Add S */P1-> next = s; s-> next = NULL ;} insert else {/* s into L */P2-> next = s; s-> next = p1;} Return OK;}/* in the single-chain linear table l, delete element I, and E returns its value */INT deletelistnode (linklist * l, int I, elemtype * E) {Int J = 0; linklist p1 = * l, p2; If (p1 = NULL | I <1)/* I less than 1 */Return Error; while (P1-> next! = NULL & J <i-1)/* Find the I-th node and Point P1 to its node */{P2 = p1; P1 = p1-> next; j ++;} If (p1 = * l) {/* Delete the first node */* l = p1-> next; * E = p1-> data; free (P1); P1 = NULL;} else {/* Delete and release the node */P2-> next = p1-> next; * E = p1-> data; free (P1); P1 = NULL;} Return OK;}/* initial condition: the linear table l already exists. Operation Result: Call the visit () function to print */void traverselist (linklist L, printfun visit) {linklist P = L; while (P) {(* visit) (p-> data); P = p-> next;} printf ("\ n");}/** reverse single-chain table 1. recursive methods are used. The basic idea of this method is to call recursive functions to reverse the subsequent nodes before reversing the current node. However, this method has one disadvantage: The last node after the inversion will form a ring, so the next field of the node returned by the function must be set to null. Because the head pointer needs to be changed, a pointer pointing to the head pointer is used. */Lnode * reverselist_recursive (lnode * P, linklist * head) {lnode * TMP; If (null = p | null = p-> next) {* head = P; return P;} else {TMP = reverselist_recursive (p-> next, head); TMP-> next = P; // note: the last two nodes after the reversal form a loop return P;} void reverselistrecursive (linklist * head) {lnode * P; if (* head = NULL | (* head)-> next = NULL) {return;} p = * head; P = reverselist_recursive (p, head ); if (islooplist (* head) = true) {// Loop P-> next = NUL L; // set the next field of the node returned by the function to null .}} /** Reverse a single-chain table 2. Use non-recursive methods. When traversing a single-chain table while reversing the pointer, three secondary pointers are required. The first two pointers are used to reverse the table, and the last one is used to traverse the single-chain table, finally, the next element of the head is empty, and the head points to the header node after the reversal. */Lnode * reverselist (linklist head) {lnode * P1, * P2, * P3; If (Head = NULL | head-> next = NULL) {return head;} p1 = head; P2 = p1-> next; P3 = P2-> next; while (null! = P3) {P2-> next = p1; P1 = P2; P2 = P3; P3 = P3-> next;} P2-> next = p1; head-> next = NULL; head = P2; return head;}/** it is known that the two linked lists head1 and head2 are in an orderly order, and they are merged into a linked list. They are still in an orderly (non-decreasing) Order) 1. recursive Method: */lnode * mergelist_recursive (linklist head1, linklist head2) {linklist head = NULL; If (null = head1) {return head2;} If (null = head2) {return head1;} If (head1-> data 

 

Test File: (C ++)

#include <iostream>#include "LinkList.h"using namespace std;int comp(ElemType a, ElemType b){if (a==b){return 0;}return (a-b)/abs(a-b);}void print(ElemType e){cout<<e<<"->";}int main(){LinkList l1,l2,l3;LNode *midNode;int iElem,dElem,Elem,pElem,nElem;int pos;createList(&l1,5);traverseList(l1,&print);cout<<"the list length:"<<ListLength(l1)<<endl;if (isEmpty(l1)==FALSE){cout<<"this is not empty list!"<<endl;}if(GetElem(l1,6,&Elem)==OK){cout<<Elem<<endl;}cout<<"Input a elem for LocalElem:"<<endl;cin>>Elem;pos = LocaleElem(l1,Elem,&comp);cout<<"the position of the elem is:"<<pos<<endl;cout<<"Input a elem for PriorElem:"<<endl;cin>>Elem;if (PriorElem(l1,Elem,&pElem)==OK){cout<<"the prior of the elem is:"<<pElem<<endl;}cout<<"Input a elem for NextElem:"<<endl;cin>>Elem;if (NextElem(l1,Elem,&nElem)==OK){cout<<"the next of the elem is:"<<nElem<<endl;}//destroyList(&l1);//if (isEmpty(l1)==TRUE)//{//cout<<"this is empty list!"<<endl;//}findMid(l1,&midNode);cout<<"midNode:"<<midNode->data<<endl;traverseList(l1,&print);cout<<"Input insertElem:"<<endl;cin>>iElem;insertListNode(&l1,3,iElem);traverseList(l1,&print);findMid(l1,&midNode);cout<<"midNode:"<<midNode->data<<endl;deleteListNode(&l1,3,&dElem);cout<<"the deleteElem:"<<dElem<<endl;traverseList(l1,&print);sortList(&l1);traverseList(l1,&print);reverseListRecursive(&l1);traverseList(l1,&print);l1 = reverseList(l1);traverseList(l1,&print);createList(&l2,5);traverseList(l2,&print);//l1 = mergeList_recursive(l1,l2);//traverseList(l1,&print);l3 = mergeList(l1,l2);traverseList(l3,&print);system("pause");return 0;}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.