Sorted insert for circular linked list

63 篇文章 0 订阅

在一个已排序的循环聊表中插入一个新节点,返回新的头节点

参考:点击打开链接

package list;

import z_dataStructure.ListNode;

//http://www.1point3acres.com/bbs/forum.php?mod=viewthread&tid=144400&extra=page%3D9%26filter%3Dsortid%26sortid%3D311%26searchoption%5B3046%5D%5Bvalue%5D%3D2%26searchoption%5B3046%5D%5Btype%5D%3Dradio%26sortid%3D311
//http://www.1point3acres.com/bbs/forum.php?mod=viewthread&tid=144124&extra=page%3D9%26filter%3Dsortid%26sortid%3D311%26searchoption%255B3046%255D%255Bvalue%255D%3D2%26searchoption%255B3046%255D%255Btype%255D%3Dradio&page=1
public class InsertNodeToCircularList {

	ListNode head = null;

	/*
	 * function to insert a new_node in a list in sorted way. Note that this
	 * function expects a pointer to head node as this can modify the head of
	 * the input linked list
	 */
	void sortedInsert(ListNode new_node) {
		ListNode current = head;

		// Case 1 of the above algo
		if (current == null) {
			new_node.next = new_node;
			head = new_node;

		}

		// Case 2 of the above algo
		else if (current.data >= new_node.data) {

			/*
			 * If value is smaller than head's value then we need to change next
			 * of last node
			 */
			while (current.next != head)
				current = current.next;

			current.next = new_node;
			new_node.next = head;
			head = new_node;
		}

		// Case 3 of the above algo
		else {

			/* Locate the node before the point of insertion */
			while (current.next != head && current.next.data < new_node.data)
				current = current.next;

			new_node.next = current.next;
			current.next = new_node;
		}
	}

	// Utility method to print a linked list
	void printList() {
		if (head != null) {
			ListNode temp = head;
			do {
				System.out.print(temp.data + " ");
				temp = temp.next;
			} while (temp != head);
		}
	}

	// Driver code to test above
	public static void main(String[] args) {
		InsertNodeToCircularList list = new InsertNodeToCircularList();

		// Creating the linkedlist
		int arr[] = new int[] { 12, 56, 2, 11, 1, 90 };

		/* start with empty linked list */
		ListNode temp = null;

		/*
		 * Create linked list from the array arr[]. Created linked list will be
		 * 1->2->11->56->90
		 */
		for (int i = 0; i < 6; i++) {
			temp = new ListNode(arr[i]);
			list.sortedInsert(temp);
		}

		list.printList();
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值