题目:203.Remove all elements from a linked list of integers that have value val.
class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head == null) return head;
while(head.val == val){
head = head.next;
if(head == null) return head;
}
ListNode cur = head;
while(cur != null && cur.next != null){
if(cur.next.val == val){
cur.next = cur.next.next;
}else{
cur = cur.next;
}
}
return head;
}
}
本人写的,自我感觉写的不太好。看了几个java代码感觉都是大同小异,没有多大变化就不罗列了。
题目206. Reverse Linked List
这里是用三指针解决的,简单但复杂。
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode per = null;
ListNode node = head;
ListNode cur = head.next;
while(true){
node.next = per;
per = node;
node = cur;
if(node == null)
return per;
cur = cur.next;
}
}
}
目标:每天一道算法题。
时间:2019-5-31
已完成:6道