253 views

To reverse a Singly Linked List is the below is correct code? (or) need to change

Struct node *reverse(struct node *start)
{
Struct node *prev,*ptr,*next;
prev=NULL;
ptr=start;
while(ptr!=NULL)
{
prev=ptr;
ptr=next;
}
start=prev;
return start;

Plz tell me, is here all link updating correctly?

edited
0
yes it is
0
Can u explain?
0
code is correct, there is no error.
0
how? give some small explaination
0
here 3 pointer. prev, ptr, next

Say there are 3 node in LL.

1---->2----->3

Now, next pointing to 2nd node

Then, ptr->link eliminated, as it is going to be NULL

Now any easy way to see, if it is reversing?
1

initially, 1 ---> 2 ---> 3

pre = next = NULL, ptr points to the element 1.

ptr != Null ===> enter into loop

1) making next as element 2

2) making element 1 --> link  = prev = NULL

3) making prev as element 1

4) making ptr as element 2

ptr != Null ===> enter into loop

1) making next as element 3

2) making element 2 --> link  = prev = element 1

3) making prev as element 2

4) making ptr as element 3

ptr != Null ===> enter into loop

1) making next as NULL due to 3 --> next = NULL

2) making element 3 --> link  = prev = element 2

3) making prev as element 3

4) making ptr as NULL

ptr != NULL ===> out of loop.

start = prev ===> making 3 as start of the linked list.

3 ---> 2 ---> 1

0
thanks

No, other short procedure, na?

We need to execute every line of code?

I am asking because,in exam  there are so many similar type option to be checked :(
0
Yes, there is no shortcut mam

We have to check each and every line
0

@Shaik Masthan

here start is pointing to last node, that is true

But is it creating reverse links too?

I mean B-->A

and C-->B?

1

yes.... due to ptr -> link = prev

0
@Shaik

will reversing linked list take O(n) time?

will find kth node from the end of a linked list take O(n)  time?
0
yes mam !

But note that there are more approaches for this query !

reverse(p=q=null)

{

while(s!=0)

{p=q;

q=s;

s=s->next;

q->next=p;

}

s=q;

return(s);

}

try this program to reverse tha single link list.

where p and q having extra 2 poniter.

## Related questions

1 vote
1
2.8k views
What would be the asymptotic time complexity to add a node at the end of singly linked list, if the pointer is initially pointing to the head of the list? (a) O(1) (b) O(n) (c) θ (n) (d) θ (1) Confused between option (b) and (c) .
1 vote
Consider an unrolled linked list with $n$ elements.This list stores multiple elements in each node. What is the worst case time complexity to find the $k^{th}$ element if the number of nodes and the number of elements in each node are equal? $A)O(n)$ $B)O(\sqrt n)$ $C)O(nlogn)$ $D)O(n^{2})$