题解 | #反转链表#
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
非常笨的方法,算上本身,三个指针来回倒腾,因为用了三个指针,特例一大堆。
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return ListNode类 */ #include <math.h> struct ListNode* ReverseList(struct ListNode* head ) { // write code here if(head == NULL) { return NULL; } if(head->next != NULL && head->next->next != NULL) { struct ListNode* head_tmp1 = head->next;//游指针 struct ListNode* head_tmp2 = head->next->next;//游指针 if(head_tmp2->next == NULL) { head->next = NULL; head_tmp1->next = head; head_tmp2->next = head_tmp1; return head_tmp2; } head->next = NULL; while(head_tmp2->next!=NULL) { head_tmp1->next = head; head = head_tmp1; head_tmp1 = head_tmp2; head_tmp2 = head_tmp2->next; } head_tmp1->next = head; head_tmp2->next = head_tmp1; return head_tmp2; } else if(head->next->next == NULL && head->next != NULL) { struct ListNode* head_tmp1 = head->next;//游指针 head->next = NULL; head_tmp1->next = head; return head_tmp1; } else { return head; } }