链表操作

记录链表操作数据

(1)新建链表

(2)插入新节点

(3)打印链表

关键问题:二级指针,链表头修改。

// ConsoleApplication11.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>

using namespace std;



typedef struct ListNode
{
    int value;
    struct ListNode *pNext;
}ListNode;

void InsertNode(ListNode **pHead, ListNode * temp);

void PrintList(ListNode ** pHead);

int _tmain(int argc, _TCHAR* argv[])
{
    cout << "新建链表" << endl;
    ListNode *pHead;
    pHead = NULL;   //初始化一个空指针作为链表头,未添加元素前为空
    int data = 0;
    (cin >> data);
    while (data != 0)
    {
        
        ListNode * temp = new ListNode;
        temp->value = data;
        temp->pNext = NULL;
        InsertNode(&pHead, temp);
        (cin >> data);
    }

    PrintList(&pHead);

    

    return 0;
}

void InsertNode(ListNode **pHead, ListNode * temp)
{
    if (pHead == NULL ||  temp == NULL)
        return;
    
    if (*pHead == NULL)
    {
        *pHead = temp;
        (*pHead)->pNext = NULL;
        return;
    }
    ListNode *p2 = NULL;
    ListNode *p1 = *pHead;
    while ( p1 != NULL && temp->value > p1->value)
    {
        p2 = p1;
        p1 = p1->pNext;
    }

    if (p1 == *pHead)
    {
        temp->pNext = *pHead;
        *pHead = temp;
    }
    else
    {
        p2->pNext = temp;
        temp->pNext = p1;
    }


    

}

void PrintList(ListNode ** pHead)

{
    if (pHead == NULL || *pHead == NULL)
        return;

    ListNode * p = *pHead;
    while (p != NULL)
    {
        cout << p->value << endl;
        p = p->pNext;
    }

}
原文地址:https://www.cnblogs.com/wll-zju/p/4830468.html