leetcode练习题 recorder-list

思路

快慢指针找到链表的中间结点,将原链表分为两部分,之后将链表的后半部分逆置,之后合并两个单链表,注意:一定要判定头部是否为空!

代码

class Solution {
public:
	void reorderList(ListNode *head) {
		if (head != NULL){
			//快慢指针求中间结点
			ListNode *slow = head;
			ListNode *fast = head;
			while (fast->next != NULL && fast->next->next != NULL){
				slow = slow->next;
				fast = fast->next->next;
			}
			//将链表的后面部分逆置
			fast = slow->next;
			slow->next = NULL;
			ListNode *new_head = new ListNode(0);
			while (fast){
				ListNode *tmp = fast->next;
				fast->next = new_head->next;
				new_head->next = fast;
				fast = tmp;
			}
			//合并
			ListNode *p = head;
			ListNode *q = new_head->next;
			while (q != NULL){
				ListNode *n = q->next;
				q->next = p->next;
				p->next = q;
				p = p->next->next;
				q = n;
			}
		}
	}
};
发布了18 篇原创文章 · 获赞 0 · 访问量 58

猜你喜欢

转载自blog.csdn.net/qq_38303368/article/details/104971993
今日推荐