Leetcode013--单链表删除操作
来源:互联网 发布:windows字体库在哪 编辑:程序博客网 时间:2024/05/26 20:24
一、原题
Given a linked list, remove the nth node from the end of list and return its head.
二、中文
删除单链表的倒数第N个结点,注意:输入的N都是合法,在一次遍历中完成操作。
三、举例
比如给出链表 1->2->3->4->5->6->7,当我们删除倒数第三个元素的后就变成了1->2->3->4->6->7
四、思路
五、程序
思路是先找到第n个元素,同时使用另一个指针指向
package LeetCode;//删除单链表的倒数第N个结点,注意:输入的N都是合法,在一次遍历中完成操作。 class ListNode { int val; ListNode next; ListNode(){ } ListNode(int x) { val = x; next = null; }}public class Leetcode014 {public static void main(String args[]){ ListNode n1 = new ListNode(1); ListNode n2 = new ListNode(2); ListNode n3 = new ListNode(3); ListNode n4 = new ListNode(4); ListNode n5 = new ListNode(5); ListNode n6 = new ListNode(6); ListNode n7 = new ListNode(7); n1.next = n2; n2.next = n3; n3.next = n4; n4.next = n5; n5.next = n6; n6.next = n7; ListNode list = new ListNode();list = reGetKthNode(n1, 3);reversePrintListRec(list);} public static void reversePrintListRec(ListNode head){ if(head==null)return; else{ while(head != null){ System.out.print(head.val+" "); head = head.next; } } } public static ListNode reGetKthNode(ListNode head,int n){ if(head == null) return null; ListNode a=head; ListNode b=head; // 找到第n个结点 for (int i = 0; i < n && a != null; i++) { a = a.next; } while(a.next!=null){ a=a.next; b=b.next; } b.next = b.next.next; return head; } }
-----------------------------------output---------------------------------------
1 2 3 4 6 7
1 0
- Leetcode013--单链表删除操作
- leetcode013
- leetcode013 Roman to Integer
- LeetCode013:Roman to Integer
- Leetcode013 Roman to Integer
- leetcode013-Maximal Square(dp)
- 单链表删除操作
- 单链表删除操作优化
- 数据结构 单链表的删除操作
- 单链表插入删除等操作
- 单链表操作---建表,查找,删除
- 删除操作
- 单链表的创建、插入、删除、倒置操作
- 单链表的创建、插入、删除、倒置操作
- 单链表操作(建表、插入、删除、查找、求表长),
- 单链表的创建、添加、删除操作
- 单链表建立,插入,删除,查找,遍历操作
- 单链表建立,插入,删除,查找,遍历操作
- 写在前面的话
- 指针
- 课堂笔记四
- ATPG中经常用到的名词 SPF
- 海量数据处理 常用思路 大公司面试题
- Leetcode013--单链表删除操作
- Android WebView
- 第11周项目2-用二叉树求解代数表达式
- E语言读取网页源码输出不全的BUG
- JQuery 上传插件 Uploadify
- UDP实现服务器与客户端通信
- 几种经典的数据排序及其Java实现
- 山崎製【せい】パン ランチ パック【pakku】 「包装袋」
- <h1>~<h6>、<a>、属性、相对路径