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; } }
标签:head,ListNode,cur,val,int,随想录,next,链表,移除 From: https://www.cnblogs.com/hewx/p/18363332