# C語言筆記 --- 這份筆記僅用於紀錄[你所不知道的 C 語言: linked list 和非連續記憶體](https://hackmd.io/@sysprog/c-linked-list)課堂中所學之內容 ``` struct ListNode *mergeTwoLists(struct ListNode *L1, struct ListNode *L2) { struct ListNode *head = NULL, **ptr = &head, **node; for (node = NULL; L1 && L2; *node = (*node)->next) { node = (L1->val < L2->val) ? &L1: &L2; *ptr = *node; ptr = &(*ptr)->next; } *ptr = (struct ListNode *)((uintptr_t) L1 | (uintptr_t) L2); return head; } ``` 最後一行的code `*ptr = (struct ListNode *)((uintptr_t) L1 | (uintptr_t) L2);` 可以參考[這是什麼黑魔法](https://facebook.com/hashtag/這是什麼黑魔法/?__gid__=1957891421058925) 重點就在於L1和L2其中一個指標已經指向NULL,透過uintptr_t的轉型,就可以將指向NULL的指標位址轉換為0 --- 以下簡單測試一下上述的狀況 ``` #include <stdio.h> #include <stdint.h> typedef struct ListNode { int val; struct ListNode *next; }ListNode; int main() { ListNode node1 = {1, NULL}; ListNode *L1 = &node1; ListNode *head=NULL, *ptr=NULL; printf("(uintptr_t) L1: %p \n", (void*)(uintptr_t) L1); printf("(ListNode *)(uintptr_t) head: %p\n", (ListNode *)(uintptr_t) head); printf("(ListNode *)(uintptr_t) L1: %p\n", (ListNode *)(uintptr_t) L1); ptr = (struct ListNode *)((uintptr_t) L1 | (uintptr_t) head); printf("ptr: %p\n", (ptr)); return 0; } ``` ouput: ``` (uintptr_t) L1: 0x7fffffffdbd0 (ListNode *)(uintptr_t) head: (nil) (ListNode *)(uintptr_t) L1: 0x7fffffffdbd0 ptr: 0x7fffffffdbd0 ``` 最後ptr也還是和L1一樣指向node1
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up