反转链表
2018-03-28 15:56
176 查看
输入一个链表,反转链表后,输出链表的所有元素。
链表结构
算法思路:
1. 若链表空,直接返回头结点
2. 若链表不为空,设置pre, cur, next三个指针,设置cur的初值为head,其余两个指针初值为空。
3. 首先令next指向cur的下一元素,然后令cur.next指向pre,完成了cur指针的反转,最后更新pre和cur;
4. 重复上述过程,直至cur==null,此时pre的值,就是原链表的最后一个元素,即新链表的第一个元素,返回pre。
具体代码如下:
链表结构
public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }
算法思路:
1. 若链表空,直接返回头结点
2. 若链表不为空,设置pre, cur, next三个指针,设置cur的初值为head,其余两个指针初值为空。
3. 首先令next指向cur的下一元素,然后令cur.next指向pre,完成了cur指针的反转,最后更新pre和cur;
4. 重复上述过程,直至cur==null,此时pre的值,就是原链表的最后一个元素,即新链表的第一个元素,返回pre。
具体代码如下:
public class Solution { public ListNode ReverseList(ListNode head) { if(head == null){ return head; } ListNode pre = null; ListNode cur = head; ListNode next = null; while(cur != null){ next = cur.next; cur.next = pre; pre = cur; cur = next; } return pre; } }
相关文章推荐
- 乙级 PAT 1025. 反转链表 (25)
- JAVA实现单向链表反转2
- 数据结构笔记--反转链表分析
- 递归和非递归实现链表反转
- 不依赖堆栈的链表反转——java实现
- 1025. 反转链表 (25)
- [LeetCode] Reverse Linked List(递归与非递归反转链表)
- 单链表反转singlelist reverse
- 单链表反转分析
- 反转链表
- 《剑指offer》面试题16—反转链表
- C/C++面试程序题(一)——字符串反转、链表反转的递归、非递归实现
- leetcode206/92---Reverse Linked List I/II(反转链表)
- 链表结构的反转(5)
- (未完成)《剑指offer》(面试题16):反转链表
- #旧代码# 基本算法练习:常见排序/KMP字符串查找/链表反转
- 链表的反转
- 链表反转的四种方法分析
- java 反转链表
- 反转链表输出