剑指offer.24 反转链表 EASY
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null||head.next==null) return head;
ListNode p=null,q=head;
while(q!=null){
ListNode next=q.next;
q.next=p;
p=q;
q=next;
}
return p;
}
}
这道题的重点是三个指针,pre,cur,next
pre一开始为空,cur为head
从头开始一步一步反转就好
时间复杂度O(n) 空间复杂度O(1)
剑指offer.25 合并两个排序的链表 EASY
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null) return l2;
if(l2==null) return l1;
ListNode head=new ListNode(0);
ListNode h=head;
while(l1!=null&&l2!=null){
if(l1.val<=l2.val){
head.next=l1;
l1=l1.next;
head=head.next;
}else{
head.next=l2;
l2=l2.next;
head=head.next;
}
}
if(l1!=null){
head.next=l1;
}else{
head.next=l2;
}
return h.next;
}
}
秒了hhhh
这道题的重点是设置一个头结点和两个指针
时间复杂度O(n+m),空间复杂度O(1)
今天第一天,就两个easy开胃hhhhh
去看球了