反转链表
题目
定义一个函数,输入一个链表的头结点,反转该链表并输出反转后链表的头结点。
思路
定义三个指针,指向当前节点的指针(pnode),指向当前节点的下一结点的指针(pnext),指向当前节点的前一节点的指针(pre,第一次初始化为空)
- 首先记录当前节点的下一结点,以为这里是更改链表中的指针,使pnode->next指向pre。所以不保存下一结点会丢失链表的信息
- 更改当前节点中next指针域,使其指向pre
- 使pre指向pnode(当前节点),pnode向后移动一个位置(pnode指向pnext)
//循环 /** * 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 == nullptr || head->next == nullptr) { return head; } ListNode *cur = head; ListNode *pre = nullptr; ListNode *new_head = nullptr; while (cur != nullptr) { ListNode *next = cur->next; if (next == nullptr) { new_head = cur; } cur->next = pre; pre = cur; cur = next; } return new_head; } }; //递归 /** * 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 == nullptr || head->next == nullptr) { return head; } ListNode *node = reverseList(head->next); head->next->next = head; head->next = nullptr; return node; } };
链表每k组翻转
List newHead(-1); newHead.next=head; List* pre=&newHead; List* end=&newHead; while(end) { List* start=nullptr; for(int i=0;i<3&&end;++i) end=end->next; if(end==nullptr) { start=pre->next; pre->next=reverse(start); break; } start=pre->next; List* next=end->next; end->next=nullptr; pre->next=reverse(start); start->next=next; pre=start; end=pre; }