LeetCode OJ 之 Remove Nth Node From End of List ( 删除链表的从尾部数第n个结点 )
2014-11-12 22:07
441 查看
题目:
Given a linked list, remove the nth node from the end of list and return its head.
删除链表的从尾部数第n个结点,返回头结点
For example,
Note:
Given n will always be valid.
Try to do this in one pass.
代码:
方法一:
Given a linked list, remove the nth node from the end of list and return its head.
删除链表的从尾部数第n个结点,返回头结点
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.
代码:
方法一:
/** * 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) { //常规思路:根据链表总长度算出倒数第n个结点位于正数第几个结点(len+1-n),再正序遍历,然后删除。 int len=1;//链表长度 ListNode *p=head; if(head == NULL || n == 0) return NULL; while(p->next != NULL)//计算链表长度 { len++; p = p->next; } if(len < n) return NULL; int num = len + 1 - n;//正着数时结点的位置 ListNode *q=head;//定义q用来记录p结点的前一个结点,方便删除 p=q->next; if(num == 1) { head = p; return head; } int i=1; while(i < num-1)//查找结点,p为要删除的结点 { q=p; p=p->next; i++; } q->next = p->next;//删除p delete p; return head; } };方法二:
/** * 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, head};//定义虚拟头结点 ListNode *p = &dummy, *q = &dummy; for (int i = 0; i < n; i++) //q先走n步 q = q->next; while(q->next) //q到达尾结点,p、q都走了len-n步,那么p就到达要删除结点的前一个结点 { p = p->next; q = q->next; } ListNode *tmp = p->next;//tmp为要删除的结点 p->next = p->next->next; delete tmp; return dummy.next; } } };
相关文章推荐
- LeetCode-Remove Nth Node From End of List-移除从链表结尾数第n个结点-双指针链表操作
- LeetCode 19 Remove Nth Node From End of List(从列表尾部删除第N个结点)(*)
- 删除链表的倒数第n个结点 Remove Nth Node From End of List
- LeetCode 19. Remove Nth Node From End of List--删除链表的倒数第n个结点
- Remove Nth Node From End of List 删除链表的倒数第n个结点
- 【LeetCode】Remove Nth Node From End of List && 【九度】题目1517:链表中倒数第k个结点
- Remove Nth Node From End of List(从链表表尾删除第n个节点)
- #19 Remove Nth Node From End of List(删除链表倒数第N个节点)
- LeetCode 19. Remove Nth Node From End of List(删除链表)
- LeetCode | Remove Nth Node From End of List(移除链表中倒数第n个结点)
- leetcode 19. Remove Nth Node From End of List 单向链表删除第n个数
- [Leetcode] remove nth node from the end of list 删除链表倒数第n各节点
- LintCode Remove Nth Node From End of List 删除链表中倒数第n个节点
- 【链表&删除倒数第K个节点】Remove Nth Node From End of List
- [LeetCode]—Remove Nth Node From End of List 删除链表的倒数第n个节点
- Remove Nth Node From End of List 从链表中删除倒数第N的节点
- 【LeetCode】Remove Nth Node From End of List 删除链表中倒数第n个节点- Easy +
- Remove Nth Node From End of List 删除链表倒数第N个节点
- LeetCodet题解--19. Remove Nth Node From End of List(删除链表的倒数第n个元素)
- LeetCode(Remove Nth Node From End of List)删除链表倒数第n个节点