10,链表
时间:2019-08-11
本文章向大家介绍10,链表,主要包括10,链表使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
题目描述:
输入一个链表,输出该链表中倒数第k个结点。
解题思路:倒数第k个节点,正数第(size-k+1) 节点
public ListNode FindKthToTail(ListNode head,int k) { if(head==null || k<=0 || k>size(head)){ return null; } int n=size(head)-k+1; while(n>1){ head=head.next; n--; } return head; } public int size(ListNode head){ int count=0; while(head!=null){ count++; head=head.next; } return count; }
解题思路二:使用两个指针,相差k个,当后面的指针到链表最后时,前面的指针最倒数第k个节点(待更新)
题目描述:
输入一个链表,反转链表后,输出新链表的表头。
public ListNode ReverseList(ListNode head) { if(head==null) return null; ListNode reversedHead=null; ListNode current=head; ListNode tmp=null; ListNode pre=null; while(current!=null){ tmp=current.next; current.next=pre; if(tmp==null) reversedHead=current; pre=current; current=tmp; } return reversedHead; }
题目三:
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则
遍历两个链表,每个值一 一比较,移动。添加
public ListNode Merge(ListNode list1,ListNode list2) { ListNode head = null; ListNode tmp = null; ListNode current = null; while(list1!=null && list2!=null){ if(list1.val>list2.val){ current=list2; list2=current.next; tmp=current; tmp.next=null;//清空插入节点的后面的值 head=add(head,tmp); }else{ current=list1; list1=current.next; tmp=current; tmp.next=null; head=add(head,tmp); } } while(list1!=null){ current=list1; list1=current.next; tmp=current; tmp.next=null; head=add(head,tmp); } while(list2!=null){ current=list2; list2=current.next; tmp=current; tmp.next=null; head=add(head,tmp); } return head; } public ListNode add(ListNode head,ListNode node){ if(head==null){ head=node; }else{ ListNode current=head; while(current.next!=null){ current=current.next; } current.next=node; } return head; }
原文地址:https://www.cnblogs.com/kobe24vs23/p/11335063.html
- JavaScript 教程
- JavaScript 编辑工具
- JavaScript 与HTML
- JavaScript 与Java
- JavaScript 数据结构
- JavaScript 基本数据类型
- JavaScript 特殊数据类型
- JavaScript 运算符
- JavaScript typeof 运算符
- JavaScript 表达式
- JavaScript 类型转换
- JavaScript 基本语法
- JavaScript 注释
- Javascript 基本处理流程
- Javascript 选择结构
- Javascript if 语句
- Javascript if 语句的嵌套
- Javascript switch 语句
- Javascript 循环结构
- Javascript 循环结构实例
- Javascript 跳转语句
- Javascript 控制语句总结
- Javascript 函数介绍
- Javascript 函数的定义
- Javascript 函数调用
- Javascript 几种特殊的函数
- JavaScript 内置函数简介
- Javascript eval() 函数
- Javascript isFinite() 函数
- Javascript isNaN() 函数
- parseInt() 与 parseFloat()
- escape() 与 unescape()
- Javascript 字符串介绍
- Javascript length属性
- javascript 字符串函数
- Javascript 日期对象简介
- Javascript 日期对象用途
- Date 对象属性和方法
- Javascript 数组是什么
- Javascript 创建数组
- Javascript 数组赋值与取值
- Javascript 数组属性和方法
- Android实现WIFI和GPRS网络的切换
- 在VS2010里快要疯掉的hello world
- gh0st源码分析与远控的编写(三)
- Android自定义View实现五星好评效果
- Android通过ViewModel保存数据实现多页面的数据共享功能
- Android自定义View实现炫酷进度条
- OpenSSL的VC编程 - MD5
- 详解AndroidStudio中代码重构菜单Refactor功能
- Android自定义View仿QQ运动步数效果
- Kotlin类型安全构建器的一次运用记录
- 两个surfaceView实现切换效果
- AndroidStudio4.0 New Class的坑(小结)
- Android日历控件的实现方法
- GetDiskFreeSpaceEx函数的一点处理
- Flutter轮播图效果的实现步骤