// 如果下标有效,则删除这个节点 publicvoiddeleteAtIndex(int index) { if (index >= size || index < 0) { return; } ListNodetemp= head; for (inti=0; i < index; i++) { temp = temp.next; } temp.next = temp.next.next; size--; } }
/** * Your MyLinkedList object will be instantiated and called as such: * MyLinkedList obj = new MyLinkedList(); * int param_1 = obj.get(index); * obj.addAtHead(val); * obj.addAtTail(val); * obj.addAtIndex(index,val); * obj.deleteAtIndex(index); */ /*单链表的具体实现思路是有的,定义,创建,初始化的各种细节都需要熟悉 不需要定义head头结点之前的虚拟节点,妈的,自动有了,get方法写错,排查了半天,浪费时间 第二遍重写花了16分钟,还有小瑕疵。边界条件index的判断
publicclassSolution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { ListNodeA= headA; ListNodeB= headB; intlenA=0; intlenB=0; while (A != null) { lenA++; A = A.next; } while (B != null) { lenB++; B = B.next; } A = headA;// 刚刚遍历长度到末尾了,再指向头结点 B = headB; if (lenA > lenB) {// 交换A,B头结点,确保A短 intt= lenA; lenA = lenB; lenB = t;
ListNodeT= A; A = B; B = T; } intd= lenB - lenA; while (d-- > 0) { B = B.next; } while (A != null) { if (A == B) { return A; } A = A.next; B = B.next; } returnnull; } }