classSolution{ public ListNode mergeKLists(ListNode[] lists){ List<Integer> nodes = new ArrayList<>(); for (int i = 0; i < lists.length; i++) { while (lists[i] != null) { nodes.add(lists[i].val); lists[i] = lists[i].next; } }
if (nodes.size() == 0) returnnull; nodes.sort(Comparator.naturalOrder()); ListNode res = new ListNode(nodes.remove(0)); ListNode p = res; for (int i = 0; i < nodes.size(); i++) { p.next = new ListNode(nodes.get(i)); p = p.next; } return res; } }
publicclassTest{ Person person = new Person("Test"); static{ System.out.println("test static"); } publicTest(){ System.out.println("test constructor"); } publicstaticvoidmain(String[] args){ new MyClass(); } } classPerson{ static{ System.out.println("person static"); } publicPerson(String str){ System.out.println("person "+str); } } classMyClassextendsTest{ Person person = new Person("MyClass"); static{ System.out.println("myclass static"); } publicMyClass(){ System.out.println("myclass constructor"); } }
/** test static myclass static person static person Test test constructor person MyClass myclass constructor */
类似地,我们还是来想一下这段代码的具体执行过程。首先加载Test类,因此会执行Test类中的static块。接着执行new MyClass(),而MyClass类还没有被加载,因此需要加载MyClass类。在加载MyClass类的时候,发现MyClass类继承自Test类,但是由于Test类已经被加载了,所以只需要加载MyClass类,那么就会执行MyClass类的中的static块。在加载完之后,就通过构造器来生成对象。而在生成对象的时候,必须先初始化父类的成员变量,因此会执行Test中的Person person = new Person(),而Person类还没有被加载过,因此会先加载Person类并执行Person类中的static块,接着执行父类的构造器,完成了父类的初始化,然后就来初始化自身了,因此会接着执行MyClass中的Person person = new Person(),最后执行MyClass的构造器。
classSolution{ public ListNode removeNthFromEnd(ListNode head, int n){ ListNode p = head; ListNode temp = head; int len = 1;
if (p == null) returnnull;
while (p.next != null) { len++; p = p.next; }
int loc = len - n; if (loc == 0) { return head.next; }
for (int i = 1; i < loc; i++) { temp = temp.next; }
temp.next = temp.next.next;
return head; } }
Pass one time and get the length of LinkedList, so just count length - n - 1 times we can find the pre pointer. All we need to do is point pre pointer.next equal the next of which pointer we should delete.
Solution Two
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution{ public ListNode removeNthFromEnd(ListNode head, int n){ List<ListNode> stack = new LinkedList<>(); ListNode temp = head;
while (temp != null) { stack.add(temp); temp = temp.next; }
ListNode[] list = stack.toArray(new ListNode[stack.size()]);
if ((list.length - n - 1) < 0) return head.next;
list[list.length - n - 1].next = list[list.length - n].next;
return head; } }
Just let the List structure give a help, we can transfer a LinkedList to an Array. So all we need to do is let list[list.length - n - 1].next equals list[list.length - n].next.
Base case: if delete the head node we just need to return head.next.