第三天是链表,要注意的是可以创建虚拟头节点来进行链表操作。
class Solution { public ListNode removeElements(ListNode head, int val) { ListNode temp = new ListNode(-1); temp.next = head; ListNode cur = temp; while(cur.next!=null){ if(cur.next.val == val){ cur.next = cur.next.next; } else{ cur = cur.next; } } return temp.next; } }
链表中基础的删除节点,创建一个虚拟节点,虚拟节点的next 为head, 然后不断next,如果这个虚拟节点的next为需要删除的数值,那么就不再指向这个节点。
class ListNode{ int val; ListNode next; public ListNode(){}; public ListNode(int val){ this.val = val; } public ListNode(int val, ListNode next){ this.val = val; this.next = next; } } class MyLinkedList { private int size; private ListNode head; public MyLinkedList() { size = 0; head = new ListNode(0); } public int get(int index) { if(index < 0 || index >= size){ return -1; } ListNode temp = head; for(int i = 0;i<= index; i++){ temp = temp.next; } return temp.val; } public void addAtHead(int val) { addAtIndex(0,val); } public void addAtTail(int val) { addAtIndex(size,val); } public void addAtIndex(int index, int val) { if(index < 0 || index > size){ return; } size ++; ListNode temp = head; for(int i = 0; i<index; i++){ temp = temp.next; } ListNode cur = new ListNode(val); cur.next = temp.next; temp.next = cur; } public void deleteAtIndex(int index) { if(index < 0 || index>= size){ return; } size--; ListNode temp = head; for(int i = 0;i < index; i++){ temp = temp.next; } temp.next = temp.next.next; } }
需要先创建一个ListNode class,然后再根据题意,实现链表的查和增删功能
class Solution { public ListNode reverseList(ListNode head) { ListNode cur = head; ListNode pre = null; ListNode post = null; while(cur != null){ post = cur.next; cur.next = pre; pre = cur; cur = post; } return pre; } }
使用两个节点来记录cur节点的前节点和后节点,然后让cur.next指向前节点
第三天结束了,目前来说第三天就开始有中等题了,对刚入门的同学可能需要花更多的时间理解
标签:ListNode,cur,temp,int,随想录,next,链表,移除 From: https://www.cnblogs.com/catSoda/p/16790264.html