大家好我是苏麟 , 今天带来LeetCode编程从0到1系列六 .
链表相关的题目 , 也是面试热题 .
大纲
- 21. 合并两个有序链表
- 206. 反转链表
21. 合并两个有序链表
描述 :
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
题目 :
LeetCode 合并两个有序链表
代码 :
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/
class Solution {public ListNode mergeTwoLists(ListNode list1, ListNode list2) {ListNode node = new ListNode(-1);ListNode p = node;while(list1 != null && list2 != null){if(list1.val <= list2.val){p.next = list1;list1 = list1.next;}else{p.next = list2;list2 = list2.next;}p = p.next;}p.next = list1 == null ? list2 : list1;return node.next;}
}
206. 反转链表
描述 :
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
题目 :
LeetCode 反转链表
代码 :
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*//**递归方法*/
class Solution {public ListNode reverseList(ListNode head) {return ssr(head);}public ListNode ssr(ListNode p){if(p == null || p.next == null){return p;}ListNode list = ssr(p.next);p.next.next = p;p.next = null;return list;}
}
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*//*** 虚拟头节点* }*/
class Solution {public ListNode reverseList(ListNode head) {if(head == null || head.next == null){return head;}ListNode dy = new ListNode(-1);ListNode temp = head;while(head != null){temp = head.next;head.next = dy.next;dy.next = head;head = temp;}return dy.next;}
}
这期就到这里 , 下期见!