206. Reverse Linked List (C語言 頭插法)
阿新 • • 發佈:2018-12-12
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
My method
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* reverseList(struct ListNode* head) { struct ListNode *new, *tmp; if (head == NULL || head->next == NULL) { return head; }
/* 獲取最後一個節點並賦值給new */ tmp = head; while (tmp->next) { tmp = tmp->next; } new = tmp; new->next = NULL; /* 遍歷head並利用頭插法將每個節點插入到new中 */ tmp = head; while (tmp != new) { struct ListNode *temp = tmp; tmp = tmp->next;//提前儲存tmp->next的地址,防止下方被覆蓋 temp->next = new->next; new->next = temp;
} return new; }
Submission Detail
27 / 27 test cases passed. |
Status:
Accepted |
Runtime: 0 ms |
Submitted: 2 minutes ago |