Created
June 21, 2018 22:56
-
-
Save Kelvinson/00870c8cfa860b58413c99eb3a7ef631 to your computer and use it in GitHub Desktop.
C++ Pointer to Pointer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// the solution by StefanPochmann https://leetcode.com/problems/swap-nodes-in-pairs/discuss/11019/7-8-lines-C++-Python-Ruby | |
ListNode* swapPairs(ListNode* head) { | |
ListNode **pp = &head, *a, *b; | |
while ((a = *pp) && (b = a->next)) { | |
a->next = b->next; | |
b->next = a; | |
*pp = b; | |
pp = &(a->next); | |
} | |
return head; | |
} | |
// Linus on Understanding Pointers: https://grisha.org/blog/2013/04/02/linus-on-understanding-pointers/ | |
typedef struct list_entry { | |
int val; | |
struct list_entry *next; | |
} list_entry; | |
list_entry *entry = head; /* assuming head exists and is the first entry of the list */ | |
list_entry *prev = NULL; | |
//in this case have to consider whether prev is null | |
while (entry) { | |
if (entry->val == to_remove) /* this is the one to remove */ | |
if (prev) | |
prev->next = entry->next; /* remove the entry */ | |
else | |
head = entry->next; /* special case - first entry */ | |
/* move on to the next entry */ | |
prev = entry; | |
entry = entry->next; | |
} | |
// now use pointer to pointer don't have to consider first node is null pointer | |
list_entry **pp = &head; /* pointer to a pointer */ | |
list_entry *entry = head; | |
while (entry) { | |
if (entry->val == to_remove) | |
*pp = entry->next; | |
pp = &entry->next; | |
entry = entry->next; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment