题目:

分别实现两个函数,一个可以删除单链表中倒数第K个节点,另一个可以删除双链表中倒数第K个节点。

要求:

如果链表长度为N,时间复杂度达到O(N),额外空间复杂度达到O(1)。

解答:

让链表从头走到尾,每移动一步,就让K值减一,当链表走到结尾时,如果K值大于0,说明不用调整链表,因为链表根本没有倒数第K个节点,此时将原链表直接返回即可;如果K值等于0,说明链表倒数第K个节点就是头结点,此时直接返回head.next,相当于删除了头结点。当K的值小于零时,再次从头结点开始走,每移动一步,就让K的值加1。当K等于0时,移动停止,移动的结到的结点就是要删除的结点的前一个结点。

链表长度为N,要删除倒数第K个节点,那么倒数第K个节点的前一个结点就是第N-K个节点。在第一次遍历之后,K的值变为了K-N。第二次遍历时,K的值不断加1.加到0就停止遍历,所在的位置就是第N-K个节点的位置。

程序:

单链表:

public static class Node {
		public int value;
		public Node next;

		public Node(int data) {
			this.value = data;
		}
	}

	public static Node removeLastKthNode(Node head, int lastKth) {
		if (head == null || lastKth < 1) {
			return head;
		}
		Node cur = head;
		while (cur != null) {
			lastKth--;
			cur = cur.next;
		}
		if (lastKth == 0) {
			head = head.next;
		}
		if (lastKth < 0) {
			cur = head;
			while (++lastKth != 0) {
				cur = cur.next;
			}
			cur.next = cur.next.next;
		}
		return head;
	}

双链表:

public static class DoubleNode {
		public int value;
		public DoubleNode last;
		public DoubleNode next;

		public DoubleNode(int data) {
			this.value = data;
		}
	}

	public static DoubleNode removeLastKthNode(DoubleNode head, int lastKth) {
		if (head == null || lastKth < 1) {
			return head;
		}
		DoubleNode cur = head;
		while (cur != null) {
			lastKth--;
			cur = cur.next;
		}
		if (lastKth == 0) {
			head = head.next;
			head.last = null;
		}
		if (lastKth < 0) {
			cur = head;
			while (++lastKth != 0) {
				cur = cur.next;
			}
			DoubleNode newNext = cur.next.next;
			cur.next = newNext;
			if (newNext != null) {
				newNext.last = cur;
			}
		}
		return head;
	}

最新文章

  1. 去IOE的一点反对意见以及其他
  2. 【转载】C#怎么判断字符是不是汉字
  3. ubuntu mysql使用
  4. IOS中限制TextField中输入的类型以及长度
  5. [原创]Keys的基本操作总结,判断Keys中是否存在Keys.Control|Keys.Alt,移除Keys中的部分键值。
  6. C# 使用微软的Visual Studio International Pack 类库提取汉字拼音首字母
  7. 【原】lua的table深拷贝
  8. Mac osx 下配置ANT
  9. Spring MVC(四)文件上传
  10. SQLServer之创建数据库快照
  11. PHP九大接口视频教程( 支付宝,QQ,短信接口,微信接口开发, 支付宝即时到账接口开发三级分销全套)
  12. EChart 文字大小调整 饼状图为例
  13. python dns
  14. CentOS 7 安装配置带用户认证的squid代理服务器
  15. [原]Jenkins(二十) jenkins再出发之Error: Opening Robot Framework log failed
  16. c#中委托与事件
  17. EditPLus添加到右键图文教程
  18. Center Alignment
  19. Exchange 2016 体系结构简介
  20. 基于FPGA的HDMI显示设计(三)

热门文章

  1. nginx访问css js 图片等静态资源,报404或无法定向访问到
  2. jmeter对响应结果做正则、json、xpath结果测试
  3. fiddler抓包工具使用图文教程
  4. python学习【第三篇】基本数据类型
  5. #1589 : 回文子串的数量(Manacher)
  6. js 自学,云知梦知识 点理论
  7. TFS二次开发-基线文件管理器(3)-源码文件的读取
  8. Webshell清除-解决驱动级文件隐藏挂马
  9. MySQL中阻塞
  10. Spring 单例