翻转链表绝对是终点项目,应该掌握的,这道题要求的是翻转一个区间内的节点,做法其实很相似,只不过要注意判定开始是头的特殊情况,这样head要更新的,还有就是要把翻转之后的尾部下一个节点保存好,要么链表就断掉了。一趟就可以,遇到节点直接翻转,最后把整个翻转的链表再翻转一次,就实现了。
class Solution { public: ListNode *reverseBetween(ListNode *head, int m, int n) { if(head == NULL || m==n) return head; ListNode *l1, *l2, *pNode = head, *pre = NULL, *nt, *ntt, *nttt; int i = 1; while(pNode){ if(i<m) {pre = pNode; i++; pNode = pNode->next;} else{ l1 = pNode; nt = l1; ntt = l1->next; l1->next = NULL; while(ntt&&i<n){ nttt = ntt->next; ntt->next = nt; nt = ntt; ntt = nttt; i++; } l2 = ntt; l1->next = l2; if(pre){ pre->next = nt; return head; }else{ return nt; } } } } };
leetcode第一刷_Reverse Linked List II,布布扣,bubuko.com
leetcode第一刷_Reverse Linked List II
原文地址:http://blog.csdn.net/u012792219/article/details/25372425