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 |