作者s860418 (水肅)
看板C_and_CPP
標題[問題] 針對pointer設pointer變數
時間Fri Jun 8 11:05:27 2018
開發平台(Platform): (Ex: Win10, Linux, ...)
Unix
編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出)
GCC-6.2.0
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
No
問題(Question):
小弟最近在leetcode上練功
自己有寫出答案,但是跑得不夠快,看一下其他高手寫的
我看到一段程式碼,他是這樣寫
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if (head == NULL || head -> next == NULL){
return head;
}
*[1;33ListNode* current = head;*[m
while (current -> next != NULL){
if (current -> val == current -> next -> val){
current -> next = current -> next -> next;
}
else{
current = current -> next;
}
}
*[1;33return head;*[m
}
};
看一下標色的字,這邊新設一個pointer變數current,assign head進來
但是return是return head
想請問一下,是不是這種設法,就是會讓current的值和head連動?
這種編法術語是什麼呢?
他的好處在哪裡呢?謝謝
餵入的資料(Input):
Input: 1->1->2
預期的正確結果(Expected Output):
Output: 1->2
錯誤結果(Wrong Output):
無
程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔)
如上
補充說明(Supplement):
leetcode 83題
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 100.8.214.54
※ 文章網址: https://webptt.com/m.aspx?n=bbs/C_and_CPP/M.1528427131.A.8E7.html
1F:推 jerryh001: 兩個無關 這樣的好處... 樓下說他知道 XD 06/08 11:43
2F:→ MOONRAKER: 我只知道你顏色跑掉了 esc要用Ctrl-U輸入(對嗎?) 06/08 11:48
3F:推 cutekid: 沒有連動唷,將重複值的link拔掉後,回傳 list 的開頭 06/08 11:57
4F:→ elements: 這題目看起來很簡單 你寫不夠快應該是因為你的演算法複 06/08 16:29
5F:→ elements: 雜度太高 然後這不是什麼特殊技巧 就只是用另一個指標 06/08 16:29
6F:→ elements: 去操作 list 06/08 16:29
7F:推 kaneson: return的問題在於傳head進去, 操作head以外的東西時沒什 06/08 17:44
8F:→ kaneson: 麼問題,而如果改到head的話就需要一個固定管道傳出來, 06/08 17:44
9F:→ kaneson: 方法有return head, 傳參數用指標的指標或pass by refere 06/08 17:44
10F:→ kaneson: nce等, 一般list操作最make sense的是return head, 在其 06/08 17:44
11F:→ kaneson: 他做法或應用時不得已(return不夠用之類的)再考慮其他做 06/08 17:44
12F:→ kaneson: 法 06/08 17:44