反转链表
描述
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
头插法
链表要注意很多细节,比如上面例子最后1的next要指向NULL,不然会无线循环,超时,还有很多细节需要注意。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==NULL || head->next==NULL)
return head;
ListNode *p = new ListNode(-1);
p->next = head;
ListNode* cur = head->next;
ListNode* next;
head->next = NULL;
while(cur != NULL)
{
next = cur->next;
cur->next = p->next;
p->next = cur;
cur = next;
}
return p->next;
}
};
迭代反转
一个cur,一个pre指向下一个结点
- ListNode* t = pre->next;
- pre->next = cur;
- cur = pre;
- pre = t;
可用例子具体分析一下会理解更透彻
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==NULL || head->next==NULL)
return head;
ListNode* cur = head;
ListNode* pre = NULL;
while(cur!=NULL)
{
ListNode* temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
};
反转链表2
描述
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL
思路和代码
和上一题不同的是设置了一个反转的区间
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
ListNode* dummy = new ListNode(-1);
ListNode* pre = dummy;
dummy->next = head;
for(int i=0; i<m-1; i++)
pre = pre->next;
ListNode* head2 = pre;
pre = pre->next;
ListNode* cur = pre->next;
for(int i=m; i<n; i++)
{
pre->next = cur->next;
cur->next = head2->next;
head2->next = cur;
cur = pre->next;
}
return dummy->next;
}
};