The list of basic operations: create, insert, delete

#include <the iostream>
 the using  namespace STD; 

// list definition 
struct ListNode 
{ 
    int Val; 
    ListNode * Next; 
    ListNode ( int n-): Val (n-), Next (nullptr a) {} 
}; 

// print the list 
void printList (* ListNode head) 
{ 
    ListNode * pT = head;
     the while (! pT = nullptr a) 
    { 
        COUT << PT-> Val << "  " ; 
        pT = PT-> Next; 
    } 
} 

//Create lists (first interpolation), note that when printing the print backwards 
ListNode * createListA (head ListNode *, int * ARR, int len) 
{ 
    ListNode * = pB head;
     for ( int I = 0 ; I <len; ++ I) 
    { 
        ListNode * pA = new new ListNode ( 0 );     // NOTE: 
        pA - a> Val = ARR [I]; 
        pA -> Next = pb-> Next; 
        pB -> Next = pA; 
    } 
    head = head-> the Next;     // Do the initial head node, otherwise it will print out 0 
    returnhead; 
} 

// list created (tail interpolation) 
ListNode * createListB (head ListNode *, int * ARR, int len) 
{ 
    ListNode * = pB head;
     for ( int I = 0 ; I <len; ++ I) 
    { 
        ListNode * pA = new new ListNode ( 0 );     // NOTE: 
        pA - a> Val = ARR [I]; 
        pB -> Next = pA; 
        pB = pA; 
    } 
    head = head-> Next;     // do the initial head node, otherwise it will print out 0
    pb-> Next = nullptr a;     // Note tail interpolation Finally blanking 
    return head; 
} 

// in the linked list node 
void insertVarofList (head ListNode *, int POS, int Val) 
{ 
    int CNT = 0 ; 
    ListNode * TEMP = new new ListNode (Val);
     the while (head =! nullptr a) 
    { 
        head = head-> Next;
         ++ CNT;
         IF (CNT == POS) 
        { 
            TEMP -> Next = head-> Next;     // Note: The order can not be changed
            head->next = temp;
            break;
        }
    }
}

//链表节点的删除
void deleteValofList(ListNode* head, int pos)
{
    int cnt = 0;
    ListNode* temp = new ListNode(0);
    while (head != nullptr)
    {
        head = head->next;
        ++cnt;
        if (cnt == pos)
        {
            temp= head->next;    //Point to the deleted node so temp 
            head-> Next = temp-> Next;
             Delete temp;
             BREAK ; 
        } 
    } 
} 

int main () 
{ 
    int ARR [] = { 10 , 15 , 96 , 18 is , 2 , 22 is , . 6 , 2 }; 
    ListNode * = head new new ListNode ( 0 ); 
    ListNode * L = createListB (head, ARR, . 8 ); 
    printList (L); 
    COUT << endl;

    insertVarofList(L, 3, 100);
    printList(L);
    cout << endl;

    deleteValofList(L, 3);
    printList(L);
    cout << endl;

    return 0;
}

 

Guess you like

Origin www.cnblogs.com/parzulpan/p/11257276.html