1.单向链表的原地反转
public class A { public A next; private int n; public A(int n) { this.n = n; } public static A reverse(A a){ A current = a.next; a.next = null; A last = a; while(true){ if (current == null) { break; }else{ A c = current.next; current.next = last; last = current; current = c; } } return last; } public static void main(String[] args) { A a1 = new A(1); A a2 = new A(2); a1.next = a2; A a3 = new A(3); a2.next = a3; A last = reverse(a1); System.out.println(last.n); System.out.println(last.next.n); System.out.println(last.next.next.n); }}
2.消除字符串中成对的括号,必须成对匹配,否则打印error
public class B{ public static void removeBrackets(char[] arr){ int leftBracket = 0; StringBuilder sb = new StringBuilder(); for (char ch : arr) { if (ch == '(') { leftBracket++; }else if(ch == ')'){ if (leftBracket == 0) { System.out.println("error"); return; }else{ leftBracket --; } }else{ sb.append(ch); } } if ( leftBracket != 0 ) { System.out.println("error"); return; } System.out.println(sb.toString()); } public static void main(String[] args) { String s = "1(23456(789)abc)"; removeBrackets(s.toCharArray()); }}
3.将长度为a的单向链表链接到长度为b的单向链表,算法复杂度是 A. O(blogb) B. O(b) C.O(a*b) D. O(logb)