/* * 带头节点 */ 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; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/tangchenchan/article/details/47212823