LeetCode 92 & 206. Reverse Linked List
来源:互联网 发布:淘宝上比较好的女装 编辑:程序博客网 时间:2024/06/06 05:18
题目206. Reverse Linked List
题意:将单链表反转
思路:从头节点开始指针逆转
具体实现见下面代码:
public class LeetCode206 { public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } public ListNode reverseList(ListNode head) { if(head == null) return head; else{ ListNode cur = head; ListNode p = head.next; cur.next = null; //反转之后头指针指向空,很重要!!! while( p != null){ System.out.println(p.val); ListNode q = p.next; p.next = cur ; cur = p; p = q; } return cur; } }}
题目92. Reverse Linked List II
题意:将单链表中一段进行反转
例如1->2->3->4->5->6 中2到4进行反转,则可以拆分为l1(1),l2(2->3->4),l3(5->6)三部分,然后对l2进行反转,然后对三者进行拼接
具体实现思路如下:
public class LeetCode92 { public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } public ListNode reverseBetween(ListNode head, int m, int n) { if(head==null || head.next==null || m >= n) return head; ListNode nhead = new ListNode(0); nhead.next = head; ListNode start = nhead; ListNode end = null; int count = 0; while(start.next != null && count < m - 1){ count++; start = start.next; } // 执行完while,此时start位于1处,即l1的最后一个元素 ListNode sta1 = start.next; // sta1即为l2的第一个元素 ListNode end2 = sta1; // 保存l2的第一个元素 ListNode a = null; ListNode b = null; // 反转l2 while(sta1 != null && count < n){ b = sta1.next; sta1.next = a; a = sta1; sta1 = b; count++; } //拼接三者 start.next = a; end2.next = b; return nhead.next; } }
0 0
- LeetCode 92 & 206. Reverse Linked List
- 【LeetCode】206.reverse linked list
- [leetcode] 206.Reverse Linked List
- [leetcode] 206. Reverse Linked List
- 206. Reverse Linked List LeetCode
- leetCode 206. Reverse Linked List
- LeetCode 206. Reverse Linked List
- LeetCode 206. Reverse Linked List
- [LeetCode]206. Reverse Linked List
- 【LeetCode】206. Reverse Linked List
- LeetCode 206. Reverse Linked List
- leetcode 206. Reverse Linked List
- 【LeetCode】206. Reverse Linked List
- leetcode 206. Reverse Linked List
- LeetCode *** 206. Reverse Linked List
- LeetCode 206. Reverse Linked List
- 【leetcode】206. Reverse Linked List
- [LeetCode]206. Reverse Linked List
- python+批量肉鸡操作
- 命令行ionic老是装不上,失败的问题
- 导入做好的java项目出现下面的错误The project cannot be built until build path errors are resolved
- Ubuntu16.04+cuda8.0+opencv3.1+anaconda2.7+caffe安装教程
- 深度优先搜索解决问题的框架
- LeetCode 92 & 206. Reverse Linked List
- MySQL数据库事务隔离级别(Transaction Isolation Level)及测试
- 深度学习之GoogleNet and ResNet
- ssh的配置
- Javascript闭包
- EChars学习笔记(二)之快速建立项目
- HTML网页开发手册
- CSU-ACM 1838: Water Pump(单调栈+前缀后缀和)
- 浅谈 Vue v-model指令的实现原理