LeetCode 第十九题 Remove Nth Node From End of List
来源:互联网 发布:移动网络玩游戏卡吗 编辑:程序博客网 时间:2024/06/05 18:56
一,问题描述
1,删除一个单链表末尾开始算起的第n个结点,然后返回该单链表。
2,例如:
输入: 1->2->3->4->5 其中n=2;
输出: 1->2->3->5;
3,解题思路:
给定两个临时结点指向头结点head,设为p和q,先让p往前先走n个结点,然后p和q同步往前走,直到p的下一个节点为空集为止,那么q的下一个节点就是要被删除的节点。使用另外一个节点node,node=q.next。然后q.next=node.next。那么q的下一个节点就被删除了。返回头结点head。
二,AC了的程序(用Java写的)
import java.util.*;class ListNode{ //定义一个结点,结点里有一个值和指向下一个结点的指针。 int val; ListNode next; ListNode(int x) { val=x; }}public class Test2{ public static void main(String []args) { ListNode head=new ListNode(1); //先给每个数建立一个结点,但是每个结点之间还没有连接起来。 ListNode node2=new ListNode(2); ListNode node3=new ListNode(3); ListNode node4=new ListNode(4); ListNode node5=new ListNode(5); head.next=node2; //这里开始对每个结点,相互连接起来,即,相邻的结点连接起来,最终形成一个单链表,头指针指向第一个结点。 node2.next=node3; node3.next=node4; node4.next=node5; ListNode list=removeNthFromEnd(head,2);//这里的n,我给赋值为2,大家可以根据需求进行赋值的。 ListNode node=list; while(node!=null) //该部分对返回结果单链表,进行输出。 { if(node.next!=null) { System.out.print(node.val+"->"); } else { System.out.print(node.val); } node=node.next; } } public static ListNode removeNthFromEnd(ListNode head, int n)//这里是关键的函数部分 { if(n==0||head==null) { return head; } if(n==1&&head==null) //要是单链表为空的,但是要删除第1个结点,直接返回空的 { return null; } ListNode p=head; //均指向第一个结点 ListNode q=head; //均指向第一个结点 for(int i=0;i<n;i++) //先让p往前移动n个结点啊 { if(p!=null) { p=p.next; } else { return head; } } if(p==null) //这里考虑到单恋表的长度不足n,那么直接删除空集 { head=head.next; return head; } while(p.next!=null)//p的下一个结点不为空,则p和q同时往前移动一个结点。 { p=p.next; q=q.next; } ListNode node=q.next; //把q的下一个结点用一个变量node标记起来。 q.next=node.next; //这里把q的下一个结点删除了。 return head; }}
运行结果:
0 0
- LeetCode 第十九题 Remove Nth Node From End of List
- LeetCode[Linked List]: Remove Nth Node From End of List
- 19. Remove Nth Node From End of List leetcode list
- [Leetcode]LeetCode 19:Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- [Leetcode] Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- leetcode 40: Remove Nth Node From End of List
- [LeetCode] Remove Nth Node From End of List
- Leetcode 19 Remove Nth Node From End of List
- [Leetcode] Remove Nth Node From End of List
- [LeetCode]Remove Nth Node From End of List
- LeetCode-Remove Nth Node From End of List
- [LeetCode] Remove Nth Node From End of List
- LeetCode 19: Remove Nth Node From End of List
- LeetCode - Remove Nth Node From End of List
- LeetCode | Remove Nth Node From End of List
- 深入研究java.lang.Class类
- 局部内部类为什么只能访问final局部变量,对于成员变量却可以随便访问?
- Latex 之table
- 字符编码之Base64/32/16编码
- Linux 下创建Oracle表空间
- LeetCode 第十九题 Remove Nth Node From End of List
- Memcache常见问题集
- Unix环境高级编程<一>:文件I-O之读写、偏移操作
- mysql设置初始密码和更改密码(ZIP文件解压安装)
- 声明与定义
- 【H.264/AVC视频编解码技术详解】 九、序列参数集Sequence Paramater Set(SPS)解析
- 外地户籍和车辆将不能在京从事“网约车”
- Java双向认证客户端报错解决
- 【IOC】Spring IOC核心源码学习