I am trying to write a program that builds a linked list and uses insertion sort to insert each new element where it belongs. The linked list then needs to be output in ascending order. I have been working on it for many hours and I still get a "Segmentation Fault" error message once I try to run it. I am trying to use an external data file that contains 10 random integers. Here is my code, can you help me debug it? I really do appreciate your help.
PROGRAM LL_SORT
IMPLICIT NONE
TYPE :: int_value
INTEGER :: value
TYPE (int_value), POINTER :: next_value
END TYPE
TYPE (int_value), POINTER :: head, tail, ptr, ptr1, ptr2
INTEGER :: InputStatus, temp
NULLIFY (head, tail)
OPEN (UNIT = 12, FILE = "numbers.dat", STATUS = "OLD", IOSTAT = InputStatus)
DO
READ (12, *, IOSTAT = InputStatus) temp
IF (InputStatus /= 0) EXIT
ALLOCATE (ptr, stat = InputStatus)
ptr%value = temp
IF (.NOT. ASSOCIATED(head)) THEN
head => ptr
tail => head
NULLIFY (ptr%next_value)
ELSE
IF (ptr%value < head%value) THEN
ptr%next_value => head
head => ptr
ELSE IF (ptr%value >= tail%value) THEN
tail%next_value => ptr
tail => ptr
NULLIFY (tail%next_value)
ELSE
ptr1 = head
ptr2 = ptr1%next_value
DO
IF (ptr%value >= ptr1%value .AND. ptr%value < ptr2%value) THEN
ptr%next_value => ptr2
ptr1%next_value => ptr
END IF
ptr1 => ptr2
ptr2 => ptr2%next_value
END DO
END IF
END IF
END DO
DO
IF (.NOT. associated (ptr)) EXIT
print *, ptr%value
ptr => ptr%next_value
END DO
END PROGRAM LL_SORT
PROGRAM LL_SORT
IMPLICIT NONE
TYPE :: int_value
INTEGER :: value
TYPE (int_value), POINTER :: next_value
END TYPE
TYPE (int_value), POINTER :: head, tail, ptr, ptr1, ptr2
INTEGER :: InputStatus, temp
NULLIFY (head, tail)
OPEN (UNIT = 12, FILE = "numbers.dat", STATUS = "OLD", IOSTAT = InputStatus)
DO
READ (12, *, IOSTAT = InputStatus) temp
IF (InputStatus /= 0) EXIT
ALLOCATE (ptr, stat = InputStatus)
ptr%value = temp
IF (.NOT. ASSOCIATED(head)) THEN
head => ptr
tail => head
NULLIFY (ptr%next_value)
ELSE
IF (ptr%value < head%value) THEN
ptr%next_value => head
head => ptr
ELSE IF (ptr%value >= tail%value) THEN
tail%next_value => ptr
tail => ptr
NULLIFY (tail%next_value)
ELSE
ptr1 = head
ptr2 = ptr1%next_value
DO
IF (ptr%value >= ptr1%value .AND. ptr%value < ptr2%value) THEN
ptr%next_value => ptr2
ptr1%next_value => ptr
END IF
ptr1 => ptr2
ptr2 => ptr2%next_value
END DO
END IF
END IF
END DO
DO
IF (.NOT. associated (ptr)) EXIT
print *, ptr%value
ptr => ptr%next_value
END DO
END PROGRAM LL_SORT