203.移除連結串列元素
方法一:直接遍歷,永遠記得處理head, 刪除連結串列必須有前驅。
/** * 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 removeElements(ListNode head, int val) { while(head != null && head.val == val){ head = head.next; } 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; } }
方法二:用dummy head.
/** * 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 removeElements(ListNode head, int val) { ListNode dummy = new ListNode(); dummy.next = head; ListNode cur = dummy; while(cur.next != null){ if(cur.next.val == val){ cur.next = cur.next.next; }else{ cur = cur.next; } } return dummy.next; } }
707.設計連結串列
class MyLinkedList { Node head; public MyLinkedList() { head = new Node(-1); } public int get(int index) { Node curr = head.next; for(int i=0;i<index && curr != null;i++) curr = curr.next; return curr==null?-1:curr.val; } public void addAtHead(int val) { Node node = new Node(val); node.next = head.next; head.next = node; } public void addAtTail(int val) { Node curr = head; while(curr.next != null) curr = curr.next; Node node = new Node(val); curr.next = node; } public void addAtIndex(int index, int val) { Node prev = head; for(int i=0;i<index && prev != null;i++) prev = prev.next; if(prev == null) return; Node node = new Node(val); node.next = prev.next; prev.next = node; } public void deleteAtIndex(int index) { Node prev = head; for(int i=0;i<index && prev != null;i++) prev = prev.next; if(prev != null && prev.next != null) prev.next = prev.next.next; } class Node { int val; Node next; public Node(int val) { this.val = val; next = null; } } }
206.反轉連結串列 =>儲存斷開的節點
/** * 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) { ListNode prev = null; ListNode temp = null; ListNode cur = head; while(cur != null){ temp = cur.next; cur.next = prev; prev = cur; cur = temp; } return prev; } }