当前位置:网站首页>C语言快速解决反转链表
C语言快速解决反转链表
2022-07-04 22:35:00 【我不是萧海哇~~~~】
反转链表
题目描述:
给定一个单链表的头结点pHead(该头节点是有值的,比如在下图,它的val是1),长度为n,反转该链表后,返回新链表的表头。
数据范围: 0≤n≤1000
要求:空间复杂度 O(1) ,时间复杂度 O(n)O(n)
如当输入链表{1,2,3}时,经反转后,原链表变为{3,2,1},所以对应的输出为{3,2,1}。
以上转换过程如下图所示:

本文介绍两种方法:
(1)就地反转
(2)双链表法
(感觉两种方法差不多…)
/*struct ListNode { int val; struct ListNode *next; }; */
//用c语言实现
struct ListNode* ReverseList(struct ListNode* pHead ) {
struct ListNode *pre=NULL;//pre指针指向已经反转好的链表的最后一个节点,最开始没有反转,所以指向null
struct ListNode *cur=pHead;//cur指针指向待反转链表的第一个节点,最开始第一个节点待反转,所以指向head
struct ListNode *nex=NULL;//用来保存断链结点,即指针指向待反转链表的第二个节点
while(cur){
nex=cur->next;
cur->next=pre;//实现断链操作
pre=cur;//反转的节点
cur=nex;//指向之前断链的节点
}
return pre;
}
//双链表实现
struct ListNode* ReverseList(struct ListNode* pHead ) {
struct ListNode *newHead=NULL;
while(pHead!=NULL){
struct ListNode *temp=pHead->next; //保存断链结点
pHead->next=newHead;//将新链表挂到访问的原链表节点之后
newHead=pHead;
pHead=temp;
}
return newHead;
}
注:还能使用栈来实现这个题,先进后出输出刚好实现反转
原文:https://blog.csdn.net/qq_46027119/article/details/124182305
边栏推荐
猜你喜欢
![[machine learning] handwritten digit recognition](/img/26/cabdc5c92035181d82f6f809e6df0f.png)
[machine learning] handwritten digit recognition

One of the commonly used technical indicators, reading boll Bollinger line indicators

Redis getting started complete tutorial: Key Management

Mongodb aggregation operation summary

【机器学习】手写数字识别

攻防世界 MISC 进阶区 hong

Redis入門完整教程:Pipeline

集群的概述与定义,一看就会

Persistence mechanism of redis

Duplicate ADMAS part name
随机推荐
Redis introduction complete tutorial: client communication protocol
Redis入门完整教程:Redis Shell
Google Earth engine (GEE) -- take modis/006/mcd19a2 as an example to batch download the daily mean, maximum, minimum, standard deviation, statistical analysis of variance and CSV download of daily AOD
Redis入门完整教程:事务与Lua
Redis入门完整教程:键管理
Analog rocker controlled steering gear
串口数据帧
Detailed explanation of heap sort code
剑指 Offer 67. 把字符串转换成整数
环境加密技术解析
【剑指offer】1-5题
常用技术指标之一文读懂BOLL布林线指标
Attack and defense world misc advanced area Hong
啃下大骨头——排序(二)
页面关闭前,如何发送一个可靠请求
Redis入门完整教程:Redis使用场景
9 - class
How can enterprises cross the digital divide? In cloud native 2.0
Redis入门完整教程:列表讲解
Hit the core in the advanced area of misc in the attack and defense world