19. Remove Nth Node From End of List

来源:互联网 发布:js调用android的方法 编辑:程序博客网 时间:2024/06/10 10:46

题目:

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.

Note:
Given n will always be valid.
Try to do this in one pass.


题意:

给定一个链表,删除从链表末尾数第n个节点。

note:

1、给定的n值一直是有效的;

2、试着使用one-pass算法实现;


思路:

设定两个都在相同位置的指针,使一个指针先走n步,之后两个指针一起往后走,当先走的那个元素到达链表末尾时,删除后走的那个元素的下一个元素即可。

代码:4ms

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* removeNthFromEnd(ListNode* head, int n) {        ListNode dummy(-1);        dummy.next = head;        ListNode *pre = &dummy, *cur = &dummy;  //定义两个指针                while(n){  //其中一个指针先走n步            pre = pre->next;            n--;        }                while(pre->next){ //当先走的指针没有走到链表末尾时,两个指针一起向后走            pre = pre->next;            cur = cur->next;        }                ListNode *tmp = cur->next; //删掉第n个元素        cur->next = tmp->next;        delete tmp;                return dummy.next;    }};

0 0
原创粉丝点击