uTank-木头
每一个你不满意的现在,都有一个你没有努力的曾经。

【题目描述】

19. 删除链表的倒数第N个节点
给定一个链表,删除链表的倒数第?n?个节点,并且返回链表的头结点。

示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.

说明:
给定的 n?保证是有效的。

进阶:
你能尝试使用一趟扫描实现吗?

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list

【提交代码】

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     struct ListNode *next;
 6  * };
 7  */
 8 
 9 struct ListNode* removeNthFromEnd(struct ListNode* head, int n){
10     int i;
11     struct ListNode *first;
12     struct ListNode *second;
13     struct ListNode *dummy;
14 
15     dummy = (struct ListNode *)malloc( sizeof(struct ListNode) );
16     dummy->next = head;
17 
18     first = dummy;
19     second = dummy;
20 
21     for( i = 0; i <= n; i++ )
22     {
23         first = first->next;
24     }
25     while ( first != NULL ) 
26     {
27         first = first->next;
28         second = second->next;
29     }
30     second->next = second->next->next;
31 
32     return dummy->next;
33 }

 

【解题思路】

注:建立一个指向头节点的哑节点,保持操作的一致性,避免对删除头节点时的特殊判断;

 

posted on 2020-07-02 15:28  uTank  阅读(145)  评论(0编辑  收藏  举报