• 寻找单项链表中间元素


    寻找单项链表中间那个元素,如果有两个则取前面一个。

     1 #include <iostream>
     2 #include <cassert>
     3 
     4 using namespace std;
     5 
     6 template<typename T>
     7 struct Node
     8 {
     9     T m_nData;
    10     Node<T> *m_pNext;
    11 };
    12 
    13 template<typename T>
    14 Node<T>* createList(const T myArray[], const int &n)
    15 //创建链表
    16 {
    17     assert(myArray && n >0);
    18     Node<T>*  pHead = new Node<T>;
    19     Node<T>* pNew = NULL;
    20     pHead->m_pNext = NULL;
    21     for (int i = 0; i < n; i++)
    22     {    
    23         pNew = new Node<T>;
    24         pNew->m_nData = myArray[i];
    25         pNew->m_pNext = pHead ->m_pNext;
    26         pHead->m_pNext = pNew;
    27     }
    28     return pHead;
    29 }
    30 
    31 template<typename T>
    32 Node<T>* retMiddle(Node<T>* myList)
    33 //获取中间元素
    34 {
    35     assert(myList);
    36     Node<T> *p = myList->m_pNext;
    37     Node<T> *q = myList->m_pNext;
    38     while (q->m_pNext && q->m_pNext->m_pNext)
    39     {
    40         p = p->m_pNext;
    41         q = q->m_pNext->m_pNext;
    42     }
    43     return p;
    44 }
    45 
    46 template<typename T>
    47 void printList(Node<T>* myList)
    48 //打印链表
    49 {
    50     assert(myList);
    51     Node<T>*p = myList->m_pNext;
    52     cout<<"List: ";
    53     while (p)
    54     {
    55         cout<<p->m_nData<<" ";
    56         p = p->m_pNext;
    57     }
    58     cout<<endl;
    59 }
    60 void main()
    61 {
    62     const int n = 2;
    63     const int myArray[n] = {1, 2};
    64     Node<int>* myList;
    65     Node<int>* mymiddle;
    66     myList = createList(myArray, n);
    67     printList(myList);
    68     mymiddle = retMiddle(myList);
    69     cout<<"Middle: "<<mymiddle->m_nData<<endl;
    70     system("pause");
    71     return;
    72 }
  • 相关阅读:
    从IL角度彻底理解回调_委托_指针
    微信个人机器人开发
    个人微信接口开发
    淘客微信接口
    python爬虫添加请求头代码实例
    用 Django 开发一个 Python Web API
    Common encryption methods and implementation in Python Python中常用的加密方法及实现
    python aes加密
    # Python语言程序设计基础
    Python语言程序设计基础——4 程序的控制结构
  • 原文地址:https://www.cnblogs.com/alpha19881007/p/201309051036_byalpha.html
Copyright © 2020-2023  润新知