一些基础数据结构,链表,栈,队列
1、反转链表
单链表
public static Node reverseLinkedList(Node head) {
Node pre = null;
Node next = null;
while (head != null) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
// 递归解法
public ListNode reverseList(ListNode head) {
if (head == null){
return head;
}
ListNode cur = reverse(head,head.next);
head.next = null;
return cur;
}
public ListNode reverse(ListNode head, ListNode next){
if (next==null){
return head;
}
ListNode temp = reverse(head.next,next.next);
next.next = head;
return temp;
}
双向链表
public static DoubleNode reverseDoubleList(DoubleNode head) {
DoubleNode pre = null;
DoubleNode next = null;
while (head != null) {
next = head.next;
head.next = pre;
head.last = next;
pre = head;
head = next;
}
return pre;
}
2、删除链表中指定的值
public Node removeValue(Head head, int num){
while(head != null){
if (head.value != num){
break;
}
head = head.next;
}
Node pre = head;
Node cur = head;
while (cur != null){
if (cur.value == num){
pre.next = cur.next;
}else{
pre = cur;
}
cur = cur.next;
}
return head;
}
递归
例子
求数组arr[L..R]中的最大值,怎么用递归方法实现
1)将[L..R]范围分成左右两半。左:[L..Mid] 右 [Mid + 1.. R]
2) 左部分求最大值,右部分求最大值
3)[L..R]范围上的最大值,是max{左部分最大值,右部分最大值}
注意:2)是个递归过程,当范围上只有一个数,就可以不用再递归了
// 求arr中的最大值
public static int getMax(int[] arr) {
return process(arr, 0, arr.length - 1);
}
// arr[L..R]范围上求最大值 L ... R N
public static int process(int[] arr, int L, int R) {
if (L == R) { // arr[L..R]范围上只有一个数,直接返回,base case
return arr[L];
}
int mid = L + ((R - L) >> 1); // 中点 1
int leftMax = process(arr, L, mid);
int rightMax = process(arr, mid + 1, R);
return Math.max(leftMax, rightMax);
}