实现单链表逆置

 

 

看到笔试和面试里很多这样的题目,于是就练习一下,温故知新。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <iostream>
#include <cstdlib>
using namespace std;
typedef struct List
{
   int data;
   struct List *next;
}listNode,*pList;
void createList(pList & list)                   //头插入法建立单链表
{
     pList head=NULL;
     int data;
     cout<<"please input a node:";
     cin>>data;
     list=(struct List *)malloc(sizeof(listNode));
     list->data=data;
     list->next=head;
     head=list;
     while(data!=9)
{
     cout<<"please input a node:";
     cin>>data;
     list=(struct List*)malloc(sizeof(listNode));
     list->data=data;
     list->next=head;
     head=list;
 
}
}
void display(pList list)                    //输出单链表
{
     pList temp;
     temp=list;
     while(temp!=NULL)
{
     if(temp->next==NULL)
     cout<<temp->data;
     else
     cout<<temp->data<<"->";
     temp=temp->next;
}
    cout<<endl;
 
}
 
void reverseList(pList& list)              //逆置单链表
{
    pList pre;
    pList temp;
    pre=list->next;                        //记录当前节点
    temp=pre->next;                         //记录下一个节点
    list->next=NULL;
    while(pre!=NULL)
{
    pre->next=list;
    list=pre;
    pre=temp;
    if(pre!=NULL)
    temp=temp->next;
     else
     break;  
}
   // pre->next=list;
   // list=pre;
}
int main()
{
    pList list=NULL;
    cout<<"create the list :"<<endl;
    createList(list);
    cout<<"output the list:"<<endl;
    display(list);
    cout<<endl;
    cout<<"reverse the List:"<<endl;
    reverseList(list);
    cout<<"output the reverse list:"<<endl;
    display(list);
    cout<<endl;
    return 0;
}

  

上面逆置算法也可以这样写:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void reverseList(pList& list)             //逆置
{
    pList pre;
    pList temp;
    pre=list->next;                    //记录当前节点
    temp=pre->next;                    //记录下一个节点
    list->next=NULL;
    while(temp!=NULL)
{
    pre->next=list;
    list=pre;
    pre=temp;
    temp=temp->next; 
}
   pre->next=list;
   list=pre;
}

  

截图:

 

posted @   xshang  阅读(929)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
阅读排行:
· 单线程的Redis速度为什么快?
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 展开说说关于C#中ORM框架的用法!
· SQL Server 2025 AI相关能力初探
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示