本文共 1365 字,大约阅读时间需要 4 分钟。
ListNode* reverseList(ListNode* head) { if (head==NULL||head->next==NULL) return head; ListNode *pre=head;ListNode *cur=pre->next; pre->next=NULL; while (cur) { ListNode *nxt=cur->next; cur->next=pre; pre=cur; cur=nxt; } return pre; }
/************************************************************************
* * Reverse a linked list from position m to n. Do it in-place and in one-pass. * * For example: * Given 1->2->3->4->5->NULL, m = 2 and n = 4, * * return 1->4->3->2->5->NULL. * * Note: * Given m, n satisfy the following condition: * 1 ≤ m ≤ n ≤ length of list. * * ************************************************************************/ListNode* reverseBetween(ListNode* head, int m, int n) { if (m==n) return head; ListNode preHead(0),*pre=&preHead; preHead.next=head; for (int i=0;inext; ListNode *cur=pre->next; for (int i=0;i next; cur->next=nxt->next; nxt->next=pre->next; pre->next=nxt; } return preHead.next; }