链表算法题

链表算法题

//Node 定义
	public static class Node {
		//值
		public int value;
		//下一个节点
		public Node next;

		public Node(int v) {
			value = v;
		}

快慢指针

1.奇数长度返回中点,偶数长度返回上中点

	public static Node midOrUpMidNode(Node head) {
		//本身head为null,含有0个,1个节点--这些边界情况
		if (head == null || head.next == null || head.next.next == null) 	{
			return head;
		}
//slow指向第一个节点
		Node slow = head.next;
//fast指向第二个节点
		Node fast = head.next.next;

		while (fast.next != null && fast.next.next != null) {
			//slow走一个,fast走两个
			slow = slow.next;
			fast = fast.next.next;
		}
		return slow;
	}

2.奇数长度返回中点,偶数长度返回下中点

	public static Node midOrDownMidNode(Node head) {
		//0个节点
		if (head == null || head.next == null) {
			return head;
		}
		//slow与fast均指向第一个节点
		Node slow = head.next;
		Node fast = head.next;
		while (fast.next != null && fast.next.next != null) {
			slow = slow.next;
			fast = fast.next.next;
		}
		return slow;
	}

3.将单链表划分为左边小于某值 中间与某值相等 右边大于某值

把链表放入数组,然后用partition

public static Node listPartition1(Node head, int pivot) {
		if (head == null) {
			return head;
		}
		//为了求得i,申请多大的空间
		Node cur = head;
		int i = 0;
		while (cur != null) {
			i++;
			cur = cur.next;
		}
		//申请数组
		Node[] nodeArr = new Node[i];
		i = 0;
		cur = head;
		for (i = 0; i != nodeArr.length; i++) {
			nodeArr[i] = cur;
			cur = cur.next;
		}
		arrPartition(nodeArr, pivot);
		for (i = 1; i != nodeArr.length; i++) {
			nodeArr[i - 1].next = nodeArr[i];
		}
		nodeArr[i - 1].next = null;
		return nodeArr[0];
	}


	public static void arrPartition(Node[] nodeArr, int pivot) {
		int small = -1;
		int big = nodeArr.length;
		int index = 0;
		while (index != big) {
			if (nodeArr[index].value < pivot) {
				swap(nodeArr, ++small, index++);
			} else if (nodeArr[index].value == pivot) {
				index++;
			} else {
				swap(nodeArr, --big, index);
			}
		}
	}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值