代码的鲁棒性

鲁棒也就是健壮和强壮的意思。它也是在异常和危险情况下系统生存的能力。代码的鲁棒性是评价代码性能的一个重要指标。在编写程序之前,能够把测试用例提前的写好,考虑到相应的问题,对鲁棒性做相应的处理是一个很重要的习惯。

剑指Offer-专题在线编程

链表中倒数第k个结点

分析

我在这里使用了栈,本题主要注意几个问题

  • 输入的链表为空
  • k为0
  • k的值大于链表长度

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import java.util.Stack;
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if ( head == null || k == 0 ){
return null;
}
int length = 0;
Stack<ListNode> stack = new Stack();
ListNode node = head;
while( node != null ){
stack.push(node);
node = node.next;
length++;
}

if( k > length )
return null;

for( int i = 1; i < k; i++ ){
stack.pop();
}
return stack.pop();
}
}

反转链表

分析

反转链表一直绕的头晕,这次看着大佬的代码,画图理解,终于有些头绪

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class Solution {
public ListNode ReverseList(ListNode head) {
if( head == null || head.next == null ){
return head;
}

ListNode pre = null;
ListNode next = null;

while( head != null ){
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}

合并两个排序链表

分析

数据结构中很常见的题目

设置head和一个哨兵cur,对比两个链表的结点通过哨兵将结点连接到head上。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
if ( list1 == null && list2 == null ) return null;

if ( list1 == null && list2 != null ) return list2;

if ( list1 != null && list2 == null ) return list1;

ListNode head = new ListNode(0);
ListNode cur = head;

while( list1 != null && list2 != null ){
if ( list1.val <= list2.val ){
cur.next = list1;
list1 = list1.next;
}else{
cur.next = list2;
list2 = list2.next;
}
cur = cur.next;
}

if ( list1 != null ) cur.next = list1;
if ( list2 != null ) cur.next = list2;

return head.next;
}
}

树的子结构

分析

这题需要注意一下子树与子结构的区别(能力有限感觉网上解释不太好,待找到好的解释再来补上)

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;

public TreeNode(int val) {
this.val = val;

}

}
*/
public class Solution {
public boolean HasSubtree(TreeNode root1,TreeNode root2) {
if ( root1 == null || root2 == null ) return false;

return subTree(root1, root2)
|| subTree(root1.left, root2)
|| subTree(root1.right, root2);
}

public boolean subTree ( TreeNode root1, TreeNode root2 ){
if ( root2 == null ) return true;

if ( root1 == null ) return false;

if ( root1.val != root2.val )
return subTree(root1.left, root2)
|| subTree(root1.right, root2);
else
return subTree(root1.left, root2.left)
&& subTree(root1.right, root2.right);
}
}