链表问题

单链表反转

ListNode* reversenode(ListNode* p)
{
	if (p == NULL || p->next == NULL)	return p;
	ListNode* cur = p;
	ListNode* pre = NULL;
	ListNode* next = p->next;
	while (next)
	{
		cur->next = pre;
		pre = cur;
		cur = next;
		next = cur->next;		
	}
	cur->next = pre;
	return cur;
}

循环链表反转

void reverselist(ListNode* a)
{
	ListNode* head = a;
	ListNode* pre = a;
	ListNode* cur = a->next;
	ListNode* next = cur->next;
	while (cur != head)
	{
		
		cur->next = pre;
		pre = cur;
		cur = next;
		next = cur->next;
	}
	cur->next = pre;
}

反转链表中从m到n

ListNode *reversemn(ListNode* p, int m, int n)
{
	if (p == NULL || p->next == NULL || m == n)	return p;
	int t = n - m;
	ListNode* prehead = new ListNode(-1);
	prehead->next = p;
	ListNode* pre = prehead;
	while (m > 1)
	{
		pre = pre->next;
		m--;
	}
	//cur指向第m-1个节点
	ListNode* dump = pre->next;
	pre->next = NULL;
	ListNode* cur = dump;
	while (t)
	{
		cur = cur->next;
		t--;
	}
	ListNode* next = cur->next;
	cur->next = NULL;
	ListNode* newd=reversenode(dump);
	pre->next = newd;
	while (newd->next)
		newd = newd->next;
	newd->next = next;
	return prehead->next;
	
}

链表按照奇数或偶数拆分

void chaifen(ListNode* head) {
	if (head == NULL || head->next == NULL)	return;
	ListNode* p1 = head;
	ListNode* p2 = head->next;
	while ((p1&&p1->next) || (p2&&p2->next))
	{
		if (p1 != NULL && p1->next != NULL){
			p1->next = p1->next->next;
			p1 = p1->next;
		}
		if (p2 != NULL && p2->next != NULL)
		{
			p2->next = p2->next->next;
			p2 = p2->next;
		}
	}
}

143 重排链表

在这里插入图片描述

先找到中间节点,然后把后半段反转,然后按照流程变换链表即可。(已收藏

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
排序链表问题是指对一个链表进行排序。其中,可以使用链表自顶向下归并排序的方法进行排序。具体过程如下: 1. 找到链表的中点,以中点为分界,将链表拆分成两个子链表。可以通过快慢指针的方式来找到链表的中点。快指针每次移动2步,慢指针每次移动1步,当快指针到达链表末尾时,慢指针指向的节点即为链表的中点。 2. 对两个子链表分别进行排序。可以使用递归的方式对子链表进行排序,直到链表为空或者只包含1个节点时,不需要再进行拆分和排序。 3. 将两个排序后的子链表合并,得到完整的排序后的链表。可以使用合并两个有序链表的方法来实现,依次比较两个链表头节点的值,将较小的节点加入到新的链表中。 4. 返回排序后的链表。 以下是Java代码示例: ```java class Solution { public ListNode sortList(ListNode head) { if (head == null || head.next == null) { return head; } ListNode slow = head, fast = head.next; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } ListNode tmp = slow.next; slow.next = null; ListNode left = sortList(head); ListNode right = sortList(tmp); ListNode dummy = new ListNode(0); ListNode curr = dummy; while (left != null && right != null) { if (left.val < right.val) { curr.next = left; left = left.next; } else { curr.next = right; right = right.next; } curr = curr.next; } curr.next = left != null ? left : right; return dummy.next; } } ``` 以上是一种解决Java排序链表问题的方法,通过链表自顶向下归并排序的思想,可以对链表进行排序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值