Leetcode ☞ 203. Remove Linked List Elements ☆ 【dummy 方法二重点掌握】 【方法三双重指针】
2016-03-08 14:55
225 查看
203. Remove Linked List Elements
My SubmissionsQuestion
Total Accepted: 54594 Total
Submissions: 194643 Difficulty: Easy
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
我的AC1,事先讨论head-val是否等于val(16ms,落后97%,击败2%):
struct ListNode* removeElements(struct ListNode* head, int val) { while(head && head->val == val){//经过此步,能确定下返回的头节点head。 head = head->next; } if (!head) return head;//此句不能落,否则runtime error struct ListNode *curr = head; while(curr->next){ if(curr->next->val == val) curr->next = curr->next->next; else curr = curr->next; } return head; }
思路:
由于有可能是【1,1,1,2】val=1的这种情况。所以先通过一次循环把首节点val=val的节点去掉,即要确定出return的head指针。
然后再接着一个个判断。
我的AC2,不用讨论头节点是谁:(12ms,落后7%,击败4%)
我发现近几个题,只要是 返回的头指针在一开始不能确定,就可以用这个方法:
struct ListNode *dummy = (struct ListNode*)malloc(sizeof(struct ListNode));
dummy->next = head;
struct ListNode *p = dummy;
即建一个指向原head的指针dummy;循环时用p->next;最终返回是dummy->next。
struct ListNode* removeElements(struct ListNode* head, int val) { struct ListNode *dummy = (struct ListNode*)malloc(sizeof(struct ListNode)); dummy->next = head; struct ListNode *p = dummy; while(p->next){ if(p->next->val == val) p->next = p->next->next; else p = p->next; } return dummy->next; }
方法三:(指向指针的指针):
struct ListNode* removeElements(struct ListNode* head, int val) { struct ListNode **curr = &head; while (*curr) { if ((*curr)->val == val) { *curr = (*curr)->next; } else { curr = &((*curr)->next); } } return head; }
看不懂的话看下面这个:(把head跟&head分开的写法,不易混)
struct ListNode* removeElements(struct ListNode* head, int val) {
struct ListNode **prev, *curr;
prev = &head;
curr = head;
while (curr) {
if (curr->val == val)
*prev = curr->next;
else
prev = &(curr->next);
curr = curr->next;
}
return head;
}其实,二级指针/双重指针的方法 跟 dummy 的思想是一样的。都是需要整一个能够指向head的东西~
相关文章推荐
- Last_Error: Slave SQL thread retried transaction 10 time(s) in vain, giving up. Consider raising the
- [小技巧] 如何自动将阿拉伯数字转换为中文大写数字
- android中跨进程通讯的4种方式
- media query ie8- 兼容实现总结
- Effiective C++ (一)
- #include "*.c"文件的妙用
- codeforces 651A Joysticks
- 算法训练 K好数
- iOS runtime的一些心得实践
- HOJ 1603 Brackets Sequence
- runtime详细使用,后续继续增加
- 解决Sublime Text 3在GBK编码下的中文乱码问题
- 在xib中通过kvc设置button的圆角
- ANDROID L - Material Design详解(主题和布局)
- Android网络请求框架之Retrofit(二)
- Apache+PHP配置运行环境(getenv的使用)
- 找出字符串中第一个只出现一次的字符
- Ubuntu下sonar的构建[未完]
- hdoj 5100 Chessboard
- online_judge_1510