目录
1.逆序链表
1. 描述与代码
给定一个单链表的头结点pHead(该头节点是有值的,比如在下图,它的val是1),长度为n,反转该链表后,返回新链表的表头。
数据范围: 0\leq n\leq10000≤n≤1000
要求:空间复杂度 O(1)O(1) ,时间复杂度 O(n)O(n) 。
struct ListNode* ReverseList(struct ListNode* pHead ) {
if(NULL == pHead)
return NULL;
struct ListNode* n1 = NULL;
struct ListNode* n2 = pHead;
struct ListNode* n3 = n2->next;
while(n2)
{
n2->next = n1;//逆向指向
n1 = n2;
n2 = n3;
if(n3)
n3 = n3->next;
}
return n1;
}
2. 图解
2.逆序指定区间翻转
1. 描述与代码
将一个节点数为 size 链表 m 位置到 n 位置之间的区间反转,要求时间复杂度 O(n)O(n),空间复杂度 O(1)O(1)。
给出的链表为1→2→3→4→5→NULL, m= 2,n=4。返回1→4→3→2→5→NULL。
struct ListNode* reverseBetween(struct ListNode* head, int m, int n) {
if(m == 1 && n == 1)
return head;
// write code here
struct ListNode* cur = (struct ListNode*)malloc(sizeof(struct ListNode));
int i = n - m;//求出要逆序的次数
struct ListNode* n1frev;
struct ListNode* n1;
struct ListNode* n2;
struct ListNode* n3;
cur->next = head;
n1frev = cur;
while (--m)
{
n1frev = n1frev->next;//找到m位置的前一个结点
}
n1 = n1frev->next;
n2 = n1->next;
n3 = n2->next;
while (i--)//逆序m 至 n之间的指针指向
{
n2->next = n1;
n1 = n2;
n2 = n3;
if (n3)
n3 = n3->next;
}
n1frev->next->next = n2;
n1frev->next = n1;
return cur->next;
}
2. 图解