leetcode 19. Remove Nth Node From End of List

来源:互联网 发布:数据库分组查询语句 编辑:程序博客网 时间:2024/05/29 19:17
//Given a linked list, remove the nth node from the end of list and return its head.//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 Solution {static class ListNode {      int val;      ListNode next;      ListNode(int x) { val = x; }}public static void main(String[] args) {ListNode a = new ListNode(1);ListNode input = a;for(int i = 0;i<1;i++){ListNode temp = new ListNode(i+2);a.next = temp;a = a.next;}ListNode result = removeNthFromEnd(input,2);while(result != null){System.out.println(result.val);result = result.next;}}public static ListNode removeNthFromEnd(ListNode head, int n) {        ListNode result = head;        int count = 1;while(head.next!=null){//统计链表节点个数        count++;        head = head.next;        }if(count == 1){//若只有一个结点,返回空return null;}int timing = count-n;if(timing == 0){//若处理结点是0,则将头节点后移一位返回result = result.next;return result;}head = result;for(int i = 1;i<timing;i++){//找到要处理的结点head = head.next;}head.next = head.next.next;//删除当前节点后的一个结点        return result;    }}

0 0
原创粉丝点击