算法与数据结构基础课第二节笔记

一些基础数据结构,链表,栈,队列

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);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值