Reverse a LinkedList
Page 1 of 1
Reverse a LinkedList
public ListNode reverse(ListNode head){
if(head==null)
return null;
if(head.next==null)
return head;
ListNode current=head;
ListNode prev=null;
ListNode temp=null;
while(current!=null){
temp=current.next;
current.next=prev;
prev=current;
current=temp;
}
return prev;
}
if(head==null)
return null;
if(head.next==null)
return head;
ListNode current=head;
ListNode prev=null;
ListNode temp=null;
while(current!=null){
temp=current.next;
current.next=prev;
prev=current;
current=temp;
}
return prev;
}
Re: Reverse a LinkedList
Recursive way:
Recursive Method:
reverseList(List, NULL)
Node * reverseList(Node *node, Node *remainder)
{
Node *tmpNode;
if (node==NULL) return remainder;
tmpNode= node->next;
node->next = remainder;
reverseList(tmpNode, node);
}
Recursive Method:
reverseList(List, NULL)
Node * reverseList(Node *node, Node *remainder)
{
Node *tmpNode;
if (node==NULL) return remainder;
tmpNode= node->next;
node->next = remainder;
reverseList(tmpNode, node);
}
Similar topics
» Reverse a String
» Reverse words in a string
» Reverse the bit of an interger (assume it has 32-bit)
» Reverse words in a string
» Reverse the bit of an interger (assume it has 32-bit)
Page 1 of 1
Permissions in this forum:
You cannot reply to topics in this forum
|
|