分割链表、奇偶链表(Leedcode 86、328)--- 技巧(构建哑结点)

86 题目

给定一个链表和一个特定值 x,对链表进行分隔,使得所有小于 x 的节点都在大于
或等于 x 的节点之前。

你应当保留两个分区中每个节点的初始相对位置。

示例:

输入: head = 1->4->3->2->5->2, x = 3
输出: 1->2->2->4->3->5

解析

这题方法很容易想到,构建两个链表,将小于x的放在一个链表,大于或等于x的放在另一个链表,最后连接两个链表。

思路简单,但是一个技巧为两个链表建立哑结点,会让代码很简洁。这个哑结点可以减少很多条件的判断。如果不采用哑结点,当只有一个值,比如[1],会很麻烦。

 public static ListNode partition(ListNode head, int x) {
		 ListNode cur = head;
		 // 构建哑结点的好处:减少条件的判断
		 ListNode startMin = new ListNode(0); // 初始化构建哑结点(第一个结点的value为0)
		 ListNode startMax = new ListNode(0); // 初始化构建哑结点(第一个结点的value为0)
		 ListNode tail1 = startMin; 
		 ListNode tail2 = startMax;
		   
		 while(cur != null ) {
			if(cur.val < x) {
				    tail1.next = cur;
					tail1 =  tail1.next;
			}	 
				 
			else {
					tail2.next = cur;
					tail2 =  tail2.next;
				}	
			  cur = cur.next;	  
		}
		tail2.next = null;//避免成环
		tail1.next = startMax.next; // 连接两个链表
		
		return startMin.next;  
	  }

328 题目

给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。请注意,这里的奇数节点和偶数节点指的是节点编号的奇偶性,而不是节点的值的奇偶性。

请尝试使用原地算法完成。你的算法的空间复杂度应为 O(1),时间复杂度应为 O(nodes),nodes 为节点总数。

示例 1:

输入: 1->2->3->4->5->NULL
输出: 1->3->5->2->4->NULL

思路与上题一样,分别建立奇链表、偶链表。使用一个num变量来判断是奇还是偶。

代码:

public static ListNode oddEvenList(ListNode head) {
		 if(head == null) {
			 return null;
		 }
		 ListNode list1 = new ListNode(0); // 奇链表
		 ListNode tail1 = list1;
		 ListNode list2 = new ListNode(0); // 偶链表
		 ListNode tail2 = list2;
		 ListNode cur = head;
		 int num = 1;
		 while(cur != null) {
			 if(num % 2 != 0) {
				 tail1.next = cur;
				 tail1 = tail1.next;
			 }else {
				 tail2.next = cur;
				 tail2 = tail2.next;
			 }
			 num++;
			 cur = cur.next;
		 }
		 // 避免成环
		 tail2.next = null;
		 // 连接奇链表与偶链表
		 tail1.next = list2.next;
		 // 返回奇链表哑结点的下一个结点
		return list1.next;   
	}
发布了229 篇原创文章 · 获赞 169 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_41257129/article/details/104033735
今日推荐