zoukankan      html  css  js  c++  java
  • 带头结点的单链表反转

     1 #include <iostream>
    2 using namespace std;
    3
    4 struct Node
    5 {
    6 public:
    7 int data;
    8 Node * pNode;
    9 };
    10
    11
    12 void CreateList(Node * Header)
    13 {
    14 cout<<"Input the node data and end by 0"<<endl;
    15 int input;
    16 int count = 0;
    17 Node * oHeader = Header;
    18 while(cin>>input)
    19 {
    20 if(input == 0)
    21 break;
    22 else
    23 {
    24 Node * T = new Node;
    25 T->data = input;
    26 T->pNode = NULL;
    27 Header->pNode = T;
    28 Header = Header->pNode;
    29 ++count;
    30 }
    31 }
    32 oHeader->data = count;
    33 cout<<"Create "<<oHeader->data<<" Nodes"<<endl;
    34 }
    35
    36 void PrintList(Node * Header)
    37 {
    38 while(Header->pNode != NULL)
    39 {
    40 Header = Header->pNode;
    41 cout<<Header->data<<" ";
    42 }
    43 cout<<endl;
    44 }
    45
    46 void ReversePrintList(Node * Header)
    47 {
    48 if(Header->pNode != NULL)
    49 ReversePrintList(Header->pNode);
    50 cout<<Header->data<<" ";
    51 }
    52
    53
    54 Node * ReverseList(Node * Header)
    55 {
    56 Node * pPre = NULL;
    57 Node * pCurr = Header->pNode;
    58 Node * pNext = pCurr->pNode;
    59 while(pNext != NULL)
    60 {
    61 pCurr->pNode = pPre;
    62 pPre = pCurr;
    63 pCurr = pNext;
    64 pNext = pNext->pNode;
    65 }
    66 pCurr->pNode = pPre;
    67 Header->pNode = pCurr;
    68
    69 }
    70 int main()
    71 {
    72 Node * Header = new Node;
    73 CreateList(Header);
    74 cout<<"Print sequence:"<<endl;
    75 PrintList(Header);
    76 cout<<"Print sequence by reverse:"<<endl;
    77 ReversePrintList(Header->pNode);
    78 cout<<endl<<"Reverse sequence and print:"<<endl;
    79 Header->pNode = ReverseList(Header);
    80 PrintList(Header);
    81 cout<<"Number of Node is "<<Header->data<<endl;
    82 return 0;
    83 }

      

  • 相关阅读:
    python 4 days
    python 3 days
    python 2 days
    Git学习1-- 简介、命令使用、添加远程仓库方法
    Week2-列表、字符串方法示例
    Week2-购物车程序
    Week2-模块初识和数据类型
    Week1-作业:用户登陆程序
    Week1-Python入门教程(后续完善中)
    Intellij IDEA(eclipse设置)常用快捷键
  • 原文地址:https://www.cnblogs.com/DanielZheng/p/2149373.html
Copyright © 2011-2022 走看看