Singly-linked list with head node head, return a middle node of linked list.
Note: If there are two middle nodes, return the second middle node.
Example 1
Input: 1->2->3->4->5->NULL // for odd node
Output: 3->4->5->NULL
Example 1
Input: 1->2->3->4->NULL // for even node
Output: 3->4->NULL
Approach
Java
public class MiddleElement {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 fmiddle = findMiddleElement(l);linkedListTraversal(fmiddle);}private static void linkedListTraversal(ListNode node) {while (node != null) {System.out.print(node.val + " ");node = node.next;}}// method to find list from middleprivate static ListNode findMiddleElement(ListNode head) {ListNode fast = head;ListNode slow = head;// iterate till end of list// and move one pointer// once and one pointer twicewhile (fast != null) {fast = fast.next;if (fast != null) {slow = slow.next;fast = fast.next;}}return slow;}}
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 find list from middleNode * findMiddleElement(Node *head){Node *fast = head;Node *slow = head;// iterate till end of list// and move one pointer// once and one pointer twicewhile (fast != NULL) {fast = fast->next;if (fast !=NULL) {slow = slow->next;fast = fast->next;}}return slow;}//function to traverse a linked//listvoid linkedListTraversal(Node *head){Node *temp=head;//iterate till we reach end of the linked//listwhile(temp!=NULL){//print the current//node datacout<<temp->data<<" ";//move to next nodetemp=temp->next;}}int main(){Node *l = new Node(1);l->next = new Node(2);l->next->next = new Node(3);l->next->next->next = new Node(4);l->next->next->next->next = new Node(5);Node *fmiddle = findMiddleElement(l);linkedListTraversal(fmiddle);}
No comments:
Post a Comment