【LeetCode】237 & 203 - Delete Node in a Linked List & Remove Linked List Elements
2015-07-26 23:03
561 查看
237 - Delete Node in a Linked List
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Supposed the linked list is
Hide Tags: Linked List
203 - Remove Linked List Elements
Remove all elements from a linked list of integers that have value val.
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Supposed the linked list is
1 -> 2 -> 3 -> 4and you are given the third node with value
3, the linked list should become
1 -> 2 -> 4after calling your function.
Hide Tags: Linked List
struct ListNode{ int val; ListNode *next; ListNode(int x):val(x), next(NULL){} }; void deleteNode(ListNode *node) { /*the main problem is that we can not know the pre ListNode of node, so we have to copy the val one by one*/ ListNode *cur=node, *post=cur->next; while(post) { cur->val=post->val; if(post->next==NULL) cur->next=NULL; else cur=post; post=cur->next; } }
203 - Remove Linked List Elements
Remove all elements from a linked list of integers that have value val.
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5
ListNode* removeElements(ListNode* head, int val) { ListNode *newhead=new ListNode(-1); newhead->next=head; ListNode *pre=newhead; ListNode *cur=head; while(cur) { if(cur->val!=val) pre=pre->next; else pre->next=cur->next; cur=cur->next; } }
相关文章推荐
- [LeetCode]Populating Next Right Pointers in Each Node
- LeetCode-Remove Nth Node From End of List
- Reverse Nodes in k-Group
- leetcode[24]:Swap Nodes in Pairs
- javascrip中parentNode和offsetParent之间的区别
- 【Leetcode】Delete Node in a LinkedList
- [Leetcode 25] Reverse Nodes in k-Group
- leetcode[117]:Populating Next Right Pointers in Each Node II
- windows下关于nodejs和npm的安装、方法,网址
- 理解inode
- leetcode[116]:Populating Next Right Pointers in Each Node
- 我的第一个Node web程序
- Node.js模板引擎学习----ejs
- Hadoop学习笔记(老版本,YARN之前),MapReduce任务Namenode DataNode Jobtracker Tasktracker之间的关系
- Leetcode 19 Remove Nth Node From End of List
- Nodejs总结
- Nodejs进程管理模块forever详解
- leetcode - Swap Nodes in Pairs
- 237、Delete Node in a Linked List [Leetcode]
- 深入浅出NodeJS笔记(三)