前言
###我做这类文档一个重要的目的还是给正在学习的大家提供方向(例如想要掌握基础用法,该刷哪些题?)我的解析也不会做的非常详细,只会提供思路和一些关键点,力扣上的大佬们的题解质量是非常非常高滴!!!
习题
1.合并两个有序链表
题目链接: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 head = new ListNode(0);ListNode node = new ListNode(0);head.next=node;while(list1!=null&&list2!=null){if(list1.val>list2.val){ListNode flag = new ListNode(list2.val);node.next = flag;node = node.next;list2 = list2.next;}else{ListNode flag = new ListNode(list1.val);node.next = flag;node = node.next;list1 = list1.next;}}if(list1!=null){node.next = list1;}if(list2!=null){node.next = list2;}return head.next.next;}
}
2.两数相加
题目链接:2. 两数相加 - 力扣(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 addTwoNumbers(ListNode l1, ListNode l2) {ListNode head = new ListNode(0);ListNode node = new ListNode(0);head.next = node;int flag = 0;while(l1!=null&&l2!=null){int sum = l1.val+l2.val;sum+=flag;flag = sum/10;sum = sum%10;ListNode flag2 = new ListNode(sum);node.next = flag2;node = node.next;l1 = l1.next;l2 = l2.next;}if(l1!=null){while(l1!=null){int sum = l1.val;sum+=flag;flag = sum/10;sum = sum%10;ListNode flag2 = new ListNode(sum);node.next = flag2;node = node.next;l1 = l1.next;}}if(l2!=null){while(l2!=null){int sum = l2.val;sum+=flag;flag = sum/10;sum = sum%10;ListNode flag2 = new ListNode(sum);node.next = flag2;node = node.next;l2 = l2.next;}}if(flag>0){ListNode flag2 = new ListNode(flag);node.next = flag2;node = node.next; }return head.next.next;}}
3.k个一组翻转链表
题目链接:25. K 个一组翻转链表 - 力扣(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 reverseKGroup(ListNode head, int k) {ListNode root = new ListNode(0);ListNode node = new ListNode(0);root.next = node;int count = 0;List<Integer> list = new ArrayList<>();while(head!=null){list.add(head.val);count++;head = head.next;if(count%k==0){for(int i = list.size()-1;i>=0;i--){ListNode flag = new ListNode(list.get(i));node.next = flag;node = node.next;}list.clear();count = 0;} }if(count>0){for(int i = 0;i<list.size();i++){ListNode flag = new ListNode(list.get(i));node.next = flag;node = node.next;} }return root.next.next;}}
后言
上面是力扣Hot100的链表专题,下一篇是该专题的其他题目,希望有所帮助,一同进步,共勉!