第一题 反转链表
看起来容易,其实逻辑蛮绕
https://blog.csdn.net/fx677588/article/details/72357389
第二题 合并两个排序的链表
https://blog.csdn.net/jsqfengbao/article/details/47190311
要注意输入空链表时候的判断
public
ListNode Merge(ListNode list1,ListNode list2) {
if``(list1 ==
null``){
return
list2;
}
if``(list2 ==
null``){
return
list1;
}
if``(list1.val <= list2.val){
list1.next = Merge(list1.next, list2);
return
list1;
}``else``{
list2.next = Merge(list1, list2.next);
return
list2;
}
}
迭代的时候其实是使用了两个指针,merge current ,merge指向了头结点,current用来迭代
if``(list1 ==
null``){
return
list2;
}
if``(list2 ==
null``){
return
list1;
}
ListNode mergeHead =
null``;
ListNode current =
null``;
while``(list1!=``null
&& list2!=``null``){
if``(list1.val <= list2.val){
if``(mergeHead ==
null``){
mergeHead = current = list1;
}``else``{
current.next = list1;
current = current.next;
}
list1 = list1.next;
}``else``{
if``(mergeHead ==
null``){
mergeHead = current = list2;
}``else``{
current.next = list2;
current = current.next;
}
list2 = list2.next;
}
}
if``(list1 ==
null``){
current.next = list2;
}``else``{
current.next = list1;
}
return
mergeHead;
第三题 树的子结构
参考 https://blog.csdn.net/qq_27139155/article/details/79450479
第四题 字符串左旋
字符串1234abcd,循环左移4位变成abcd1234,思路先将1234逆序4321abcd,再将abcd逆序 4321dcba,然后整个逆序变成abcd4321
public static StringBuffer swap(StringBuffer arr,int a,int b) {
if(a<0||b<0) return null;
char temp;
int n = (a+b+1)/2;
System.out.println("a is :"+a);
System.out.println("b is :"+b);
for(;a<n;a++,b--) {
temp = arr.charAt(a);
arr.setCharAt(a, arr.charAt(b));
arr.setCharAt(b, temp);
System.out.println("teh result is2:"+arr);
}
System.out.println("teh result is1:"+arr);
return arr;
}
public static StringBuffer kswap(String str,int k) {
if(str==null) return null;
if(k<0) return null;
StringBuffer arrtemp = new StringBuffer(str);
System.out.println("k is :"+k);
arrtemp = swap(arrtemp,0,k-1);
//System.out.println("teh result is1:"+arrtemp);
arrtemp = swap(arrtemp,k,str.length()-1);
return swap(arrtemp,0,str.length()-1);
}