LeetCode:Remove Nth Node From End of List
来源:互联网 发布:sql server 数据库教程 编辑:程序博客网 时间:2024/06/04 23:33
问题不是太难,但是得注意,移除的第n个结点是从链表结尾算起。
算法思路:
1)首先判断链表head是否为空,或者n是否大于0;
2)统计链表长度length,将从尾部算起待移除的第n个结点转化为从链表首部开始的第target个结点;
(taget=ListLength+1-n)
3) 判断是否删除的是头结点;
4)对链表进行遍历,找到第target结点进行删除;
(添加变量before_head,用于存放当前结点的前个结点地址)
给出算法源码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */struct ListNode* removeNthFromEnd(struct ListNode* head, int n) { int ListLength; int count=0; int target; struct ListNode *c_head=head; struct ListNode *before_head; if(n<0 || head==NULL) { printf("something wrong in call\n"); exit(-1); } //calculate the list length for( ; c_head!=NULL; c_head=c_head->next) { count++; } ListLength=count; c_head=head; target=ListLength+1-n; if(target==1)//delete the head { head=head->next; free(c_head); return head; } for(count=0,before_head=c_head; c_head!=NULL; c_head=c_head->next ) { count++; if(count==target) { before_head->next=c_head->next; free(c_head); return head; } if(count==1) { before_head=before_head; } else { before_head=before_head->next; } } if(count==ListLength) { printf("not found that node\n"); exit(-1); } }
0 0
- LeetCode[Linked List]: Remove Nth Node From End of List
- 19. Remove Nth Node From End of List leetcode list
- [Leetcode]LeetCode 19:Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- [Leetcode] Remove Nth Node From End of List
- LeetCode: Remove Nth Node From End of List
- leetcode 40: Remove Nth Node From End of List
- [LeetCode] Remove Nth Node From End of List
- Leetcode 19 Remove Nth Node From End of List
- [Leetcode] Remove Nth Node From End of List
- [LeetCode]Remove Nth Node From End of List
- LeetCode-Remove Nth Node From End of List
- [LeetCode] Remove Nth Node From End of List
- LeetCode 19: Remove Nth Node From End of List
- LeetCode - Remove Nth Node From End of List
- LeetCode | Remove Nth Node From End of List
- leetcode之Remove Nth Node From End of List
- Hadoop+HBase+ZooKeeper分布式集群环境搭建
- HTML基础标签
- ORA-4031错误 解决方法
- linux学习笔记1
- 一步一步学习多线程编程之线程同步通信
- LeetCode:Remove Nth Node From End of List
- 【Python 学习手册笔记】Python 语句简介
- POJ3620
- extern "C"
- Eclipse缺少字体解决办法
- hdu 1266 Reverse Number
- android fragment学习总结
- 如何解决因为使用了注解而导致的cannot resolve method
- leetcode 日经贴,Cpp code -Sliding Window Maximum