Write a program to reverse a linked list.
Example
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Approach
Java
public class LinkListReverse {public static void main(String[] args) {ListNode l = new ListNode(1);l.next = new ListNode(2);l.next.next = new ListNode(3);l.next.next.next = new ListNode(4);l.next.next.next.next = new ListNode(5);ListNode node = reverseList(l);while (node != null) {System.out.print(" " + node.val);node = node.next;}}public static ListNode reverseList(ListNode head) {if (head == null || head.next == null)return head;ListNode c = head;ListNode prev = null;while (c != null) {ListNode n = c.next;c.next = prev;prev = c;c = n;}return prev;}}class ListNode {int val;ListNode next;ListNode() {}ListNode(int val) {this.val = val;}ListNode(int val, ListNode next) {this.val = val;this.next = next;}}//Time Complexity: O(n)//Space Complexity:O(1)
C++
#include <bits/stdc++.h>using namespace std;//Struture of nodestruct Node{int data;Node *next;Node(int data){this->data=data;this->next=NULL;}};//Function to reverse the linklistNode *reverseList(Node *head){if(head==NULL)return head;Node *curr=head,*prev=NULL,*temp=head;while(curr!=NULL){temp=curr->next;curr->next=prev;prev=curr;curr=temp;}return prev;}int main(){Node *head=new Node(1);head->next=new Node(2);head->next->next=new Node(3);head->next->next->next=new Node(4);head->next->next->next->next=new Node(5);head=reverseList(head);Node *temp=head;cout<<"Reverse List is\n";while(temp!=NULL){cout<<temp->data<<" ";temp=temp->next;}return 0;}//Time Complexity: O(n)//Space Complexity:O(1)
No comments:
Post a Comment