zoukankan      html  css  js  c++  java
  • 链表操作

    记录链表操作数据

    (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;
        }
    
    }
  • 相关阅读:
    书单
    将博客搬至CSDN
    《当我谈跑步时,我谈些什么》读后笔记
    jQuery EasyUI 教程-Tabs(选项卡)
    jqGrid中的formatter
    jqGrid中的编辑
    struts2中action接收参数的方法
    Hibernate基础(4):基础配置@Table@Column@Temporal@Transient@Enumerated
    Hibernate @Temporal
    搭建python项目
  • 原文地址:https://www.cnblogs.com/wll-zju/p/4830468.html
Copyright © 2011-2022 走看看