[LeetCode]203 Remove Linked List Elements
2015-09-26 15:45
232 查看
原题链接
Example
Given: 1 –> 2 –> 6 –> 3 –> 4 –> 5 –> 6, val = 6
Return: 1 –> 2 –> 3 –> 4 –> 5
Question
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
My Answer
struct ListNode* removeElements(struct ListNode* head, int val) { struct ListNode* cur = head; struct ListNode* pre = NULL; while(cur){ if(cur->val == val){ if(pre){ pre->next = cur->next; free(cur); cur = pre->next; }else{ //the value of the first node is equal to the given val. head = cur->next; //free(cur); cur = head; } }else{ pre = cur; cur = cur->next; } } return head; }
the complete code
#include <stdio.h>
#include <stdlib.h>
//definition for the singly-linked list.
struct ListNode{
int val;
struct ListNode *next;
};
void build(struct ListNode* head, int* nums, int numsSize){
struct ListNode *p, *q;
p = head;
for(int i=0; i<numsSize; ++i){
q = (struct ListNode*)malloc(sizeof(struct ListNode));
q->next = NULL;
q->val = nums[i];
p->next = q;
p = q;
}
}
void print(const struct ListNode* head){
struct ListNode* p = head->next;
while(p != NULL){
printf("%d ", p->val);
p = p->next;
}
printf("\n");
}
struct ListNode* removeElements(struct ListNode* head, int val) { struct ListNode* cur = head; struct ListNode* pre = NULL; while(cur){ if(cur->val == val){ if(pre){ pre->next = cur->next; free(cur); cur = pre->next; }else{ //the value of the first node is equal to the given val. head = cur->next; //free(cur); cur = head; } }else{ pre = cur; cur = cur->next; } } return head; }
int main()
{
struct ListNode* L = (struct ListNode*)malloc(sizeof(struct ListNode));
L->next = NULL;
L->val = -1;
int A[] = {1,1};
//int A[] = {};
build(L, A, 2);
print(L);
struct ListNode* head = removeElements(L, 1);
print(head);
return 0;
}
相关文章推荐
- poj3624charm bracelet【背包】
- 浅谈2015新版 U-Boot
- C基础--队列的构造
- linux安装mysql
- iOS基础-UIControl及其子类
- 剑指Offer-5-从尾到头打印链表
- RARP逆地址解析协议
- oracle 使用技巧
- poj_1836 动态规划
- cocos2d-x3.2 studio -------- 打包apk
- 【UML】概述
- 从DRP架构进行简单工厂代替抽象工厂的SWOT分析
- 1.1 VM中CentOS7通过NAT方式设置静态IP
- HDOJ1002题A + B Problem II,2个大数相加
- Html 5 坦克大战(韩顺平县版本号)
- HDOJ1002题A + B Problem II,2个大数相加
- 懒加载(转)
- 在O(1)时间删除链表结点
- hdu 3449 (有依赖的01背包)
- 如何用jQuery实现ASP.NET GridView折叠伸展效果