Converting Linked list to Array


  • 0
    S

    I have converted the linked list to array and then applied insertion sorting and then again converted back the array to linked list.

    public ListNode insertionSortList(ListNode head) {
            if (head == null || head.next == null)
    			return head;
    		ListNode curr = head;
    		//Converting Linked list to array 
    		int[] arr = new int[length(head)];
    		for (int i = 0;curr != null;i++) {
    			arr[i] = curr.val;
    			curr = curr.next;
    		}
    		
    		//Sorting the array using insertion sort
    		sorting(arr);
    		
    		//Comverting back the sorted array to Linked list
    		ListNode newHead = new ListNode(0);
    		ListNode result = newHead;
    		
    		for (int num : arr) {
    			result.next = new ListNode(num);
    			result = result.next;
    		}
    		
    		return newHead.next;
        }
        
        //Method to calculate the length of the linked list
        public int length (ListNode head) {
    		if (head == null)
    			return 0;
    		int len = 0;
    		while (head != null) {
    			len++;
    			head = head.next;
    		}
    		return len;
    	}
        
        //Insertion sort method to sort array
        public int[] sorting(int[] arr) {
    		int temp;
    		for (int i = 0;i < arr.length;i++) {
    			for (int j = i;j > 0;j--) {
    				if (arr[j] < arr[j - 1]) {
    					temp = arr[j];
    					arr[j] = arr[j - 1];
    					arr[j - 1] = temp;
    				}
    			}
    		}
    		return arr;
    	}
    

    Any Suggestions for improvement will be appreciated!


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.