单链表翻转的几种写法

来源:互联网 发布:交换机端口电压 编辑:程序博客网 时间:2024/06/14 07:41
/* * 带头节点 */ListNode * reverse(ListNode *head) {if (head == NULL || head->next == NULL)return head;ListNode nhead(-1);//头节点nhead.next = head;ListNode *prev = head;ListNode *next = head->next;while (next != NULL) {prev->next = next->next;next->next = nhead.next;nhead.next = next;next = prev->next;}return nhead.next;}//不带头结点ListNode* reverse2(ListNode *head){if(head == NULL || head->next == NULL)return head;ListNode *prev = head;ListNode *cur = prev->next;ListNode *next = cur->next;while(cur != NULL){cur->next = prev;prev = cur;cur = next;next = next ? next->next : NULL;}head->next = NULL;return prev;}
ListNode *reverseList(ListNode *head) {ListNode *pre = NULL, *next = NULL;while (head) {next = head->next;head->next = pre;pre = head;head = next;}return pre;}


0 0