定义三个指针,遍历一遍即可反转
/*** Definition for singly-linked list.* struct ListNode {* int val;* struct ListNode *next;* };*/struct ListNode* reverseList(struct ListNode* head){if (head == NULL) return NULL;if (head->next == NULL) return head;struct ListNode *p1=head, *p2=head->next;if (head->next->next == NULL) {p2->next=p1;p1->next=NULL;return p2;}struct ListNode *p3=head->next->next;p1->next=NULL;while(p2!=NULL) {p2->next=p1;p1=p2;p2=p3;if (p2!=NULL)p3=p2->next;}return p1;}
leedcode通过,效率还可以:
执行用时:4 ms, 在所有 C 提交中击败了83.92% 的用户内存消耗:6.3 MB, 在所有 C 提交中击败了50.25% 的用户
