赞
踩
注意:×
curr.next!=null && curr.next.val == val
进行判断删除/** * 不添加虚拟节点方式 * 时间复杂度 O(n) * 空间复杂度 O(1) * @param head * @param val * @return */ public ListNode removeElements(ListNode head, int val) { while (head != null && head.val == val) { head = head.next; } // 已经为null,提前退出 if (head == null) { return head; } // 已确定当前head.val != val ListNode pre = head; ListNode cur = head.next; while (cur != null) { if (cur.val == val) { pre.next = cur.next; } else { pre = cur; } cur = cur.next; } return head; } /** * 不添加虚拟节点and pre Node方式 * 时间复杂度 O(n) * 空间复杂度 O(1) * @param head * @param val * @return */ public ListNode removeElements(ListNode head, int val) { while(head!=null && head.val==val){ head = head.next; } ListNode curr = head; while(curr!=null){ while(curr.next!=null && curr.next.val == val){ curr.next = curr.next.next; } curr = curr.next; } return head; } // 自己的 public ListNode removeElements(ListNode head, int val) { while (head != null && head.val == val) { head = head.next; } ListNode dummy = head; while (dummy != null) { if (dummy.next!=null && dummy.next.val == val) { dummy.next = dummy.next.next; }else{dummy = dummy.next;} } return head; }
注意:√
head.next
,这里是为了得到这个下标对应的节点next
public class Solution { //用于存储数组中元素个数 int size; // 虚拟的头结点 ListNode head; public Solution() { size = 0; head = new ListNode(0); } public int get(int index) { // 这个函数里面的下标得反复屡清楚 if (index>=size){return -1;} int i = 0; ListNode cur = head.next; while (i<index){ cur = cur.next; i++; } return cur.var; } public void addAtHead(int val) { ListNode newNode = new ListNode(val); newNode.next = head.next; head.next = newNode; size++; } public void addAtTail(int val) { ListNode newNode = new ListNode(val); ListNode cur = head; int i = 0; while (i<size){ cur = cur.next; i++; } cur.next = newNode; size++; } public void addAtIndex(int index, int val) { if (index>size){return;} if (index == size){addAtTail(val);return;} ListNode newNode = new ListNode(val); int i = 0; // 注意这里要得到的是目标节点的上一个节点 ListNode cur = head; while (i<index){ cur = cur.next; i++; } newNode.next = cur.next; cur.next = newNode; size++; } public void deleteAtIndex(int index) { if (index>=size){return;} int i = 0; // 注意这里要得到的是目标节点的上一个节点 ListNode cur = head; while (i<index){ cur = cur.next; i++; } cur.next = cur.next.next; size--; } } class ListNode{ int var; ListNode next; public ListNode() { } public ListNode(int var) { this.var = var; } public ListNode(int var, ListNode next) { this.var = var; this.next = next; } }
注意:×
temp = temp.next;
报空指针错误,这里的问题是没有理解到temp只对cur负责,只需要负责cur的下一个位置就可以了class Solution { public ListNode reverseList(ListNode head) { // if (head == null){return null;} // if (head.next == null){return head;} ListNode pre = null; ListNode cur = head; ListNode temp = null; while (cur != null){ temp = cur.next; cur.next = pre; pre = cur; cur = temp; //temp = temp.next; } //return cur; return pre; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。