单链表翻转的几种写法

单链表翻转的几种写法

分类:数据结构与算法

单链表链表翻转

/* * 带头节点 */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

,总有看腻的时候,不论何等荣华的身份,

单链表翻转的几种写法

相关文章:

你感兴趣的文章:

标签云: