[Leetcode] Remove Nth Node From End of List (Java)
2013-12-26 12:36
323 查看
Given a linked list, remove the nth node from the end of list and return its head.
For example,
链表操作,多加几个标志指针就比较容易解决了
For example,
Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5.
链表操作,多加几个标志指针就比较容易解决了
public class RemoveNthNodeFromEndofList { static class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; } } public ListNode removeNthFromEnd(ListNode head, int n) { ListNode index = head; ListNode temp = head; ListNode res = new ListNode(0); res.next = head; ListNode pre = res; while(n!=1) { temp = temp.next; n--; } while(temp.next!=null) { pre = index; index = index.next; temp = temp.next; } pre.next = index.next; return res.next; } public static void main(String[] args) { ListNode head = new ListNode(1); // ListNode l2 = new ListNode(2); // ListNode l3 = new ListNode(3); // ListNode l4 = new ListNode(4); // ListNode l5 = new ListNode(5); // head.next=l2; // l2.next=l3; // l3.next=l4; // l4.next=l5; int n = 1; ListNode res = new RemoveNthNodeFromEndofList().removeNthFromEnd(head, n); if(res!=null){ System.out.print(res.val); res=res.next; } while(res!=null){ System.out.print("->"+res.val); res=res.next; } } }
相关文章推荐
- [LeetCode-Java]19. Remove Nth Node From End of List
- LeetCode 19 — Remove Nth Node From End of List(C++ Java Python)
- 【LeetCode-面试算法经典-Java实现】【019-Remove Nth Node From End of List(移除单链表的倒数第N个节点)】
- 【JAVA、C++】LeetCode 019 Remove Nth Node From End of List
- Leetcode:19. Remove Nth Node From End of List(JAVA)
- LeetCode : Remove Nth Node From End of List [java]
- [LeetCode][Java] Remove Nth Node From End of List
- LeetCode 19 : Remove Nth Node From End of List (Java)
- Remove Nth Node From End of List---leetcode 我的java题解
- leetcode Remove Nth Node From End of List(Java)
- LeetCode – Remove Nth Node From End of List (Java)
- leetcode:Remove Nth Node From End of List 【Java】
- (Java)LeetCode-19. Remove Nth Node From End of List
- LeetCode 19 Remove Nth Node From End of List (C,C++,Java,Python)
- Remove Nth Node From End of List leetcode java
- 19. Remove Nth Node From End of List leetcode java
- 【小熊刷题】Remove Nth Node From End of List <Leetcode 19, Java>
- [leetcode]19. Remove Nth Node From End of List@Java解题报告
- leetcode 19. Remove Nth Node From End of List---java
- Remove Nth Node From End of List leetcode java