剑指 Offer 18. 删除链表的节点
这道题为easy,利用的是单项链表删除元素的方法
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode deleteNode(ListNode head, int val) {
//temp 索引
ListNode temp = head;
ListNode pre = head;
//删除头节点的情况
if(head.val == val){
head.val = head.next.val;
head.next = head.next.next;
//return head.next; 这是一句代码的写法
}
while(temp.next!=null){
if(temp.next.val == val){
temp.next = temp.next.next;
return head;
}
temp = temp.next;
}
return head;
}
}
合并两个有序链表
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
/**
* 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) {
ListNode temp1 = l1;
ListNode temp2 = l2;
ListNode pro = new ListNode(-1);//新建一个链表表头,方便重组
//常规的temp索引
ListNode temp = pro;
if(temp2 == null) return temp1;
if(temp1 == null) return temp2;
while(temp2!=null&&temp1!=null){
if(temp1.val<=temp2.val){
temp.next = temp1;
temp1 = temp1.next;
}else{
//[1--c---3----5]
temp.next =temp2;
temp2 = temp2.next;
}
temp = temp.next;
}
//结尾是盲点
//最后一位数可能会漏掉,一个判断完美解决!!
if(temp1!=null){
temp.next =temp1;
}
if(temp2!=null){
temp.next = temp2;
}
return pro.next;
}
}