反转链表
2017-01-14 21:17
190 查看
题目描述
输入一个链表,反转链表后,输出链表的所有元素。数据结构:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
注意事项:
输入链表头指针为空,或者整个链表只有一个结点的时候,程序是否会崩溃。
反转后的链表出现断裂。
返回的反转之后的头结点不是原来的尾结点。
解法:
从头到尾遍历所有结点,利用头插法将整个链表反转。
代码如下:
public ListNode ReverseList(ListNode head) {
if (head == null){
return null;
}
ListNode pre = null;
ListNode next = null;
while(head !=null){
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
相关文章推荐
- c++STL值assign
- 关于Activity向Fragment传值的问题
- 【Webview相关问题】登陆失败之cookie陷阱
- [Tkinter 教程12] 布局管理 (Pack Place Grid)
- CentOS Linux服务器安全设置
- Gym - 101102B B. The Little Match Girl 贪心、数论、分步
- 1016. 部分A+B (15)
- MVC与WebForm的区别
- spring mvc详解
- CentOS服务器安全配置策略
- 设计模式之组合模式
- 轮廓描边效果
- VC资源编辑器里对话框的大小和实际的像素尺寸显示问题 .
- POJ2184:Cow Exhibition(类01背包)
- 九度 oj 题目1087:约数的个数
- Dom4j的使用(全而好的文章)
- Netty基础知识
- Yii setFlash getFlash用法
- Kali2.0 2016.2下VMtools的安装
- 【牛客网】滴滴出行2017秋招测试岗笔试真题汇总