链表-Reverse Linked List
2024-10-16 22:03:41
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head) {
if(!head||!head->next)
return head;
struct ListNode *cur=head;
struct ListNode *tail=head;
while(tail->next)
tail=tail->next;
while(cur!=tail)
{
head=cur->next;
cur->next=tail->next;
tail->next=cur;
cur=head;
}
return head;
}
有一个问题,leetcode给出的链表测试数据应该是不包含头结点,所以写代码的时候需要注意一下。
还有另外一种解法,就是把所有指针的方向反过来,代码如下。
struct ListNode* reverseList(struct ListNode* head) {
if(head&&head->next)
{
struct ListNode* pre=NULL;
struct ListNode* cur=head;
struct ListNode* pnext=cur->next; while(pnext)
{
cur->next=pre;
pre=cur;
cur=pnext;
pnext=cur->next;
}
cur->next=pre;
head=cur;
}
return head;
}
最新文章
- 3.Windows Server 2012 R2数据库部署
- NK3C系统中ID的汉语名称
- kali 忘记登录密码后重置的方法
- odoo报表条码无法显示解决[转]
- jquery 获取radio选中的值
- iframe标签用法详解(属性、透明、自适应高度)
- PHP中用下划线开头的变量含义
- JAXB - Hello World
- JSF学习五Ajax
- C#6.0语法糖
- vs2010编译live555源码
- 验证API
- 学好php可以做的事情真多!
- Node.js系列文章:编写自己的命令行界面程序(CLI)
- codeforces#1132 F. Clear the String(神奇的区间dp)
- ES6 - Map
- 笨鸟先飞之ASP.NET MVC系列之过滤器(04认证过滤器)
- 大数据学习笔记02-HDFS-常用命令
- 【转】vue.js表单校验详解
- 每日英语:Chinese Show Global Real-Estate Appetite