Skip to content

Commit 9d1626b

Browse files
author
ishan.gupta
committed
reverse linked list
1 parent b45b0a5 commit 9d1626b

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

reverse-linked-list.cpp

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
using namespace std;
2+
#include <iostream>
3+
#include <bits/stdc++.h>
4+
5+
struct ListNode {
6+
int val;
7+
ListNode *next;
8+
ListNode() : val(0), next(nullptr) {}
9+
ListNode(int x) : val(x), next(nullptr) {}
10+
ListNode(int x, ListNode *next) : val(x), next(next) {}
11+
};
12+
13+
class Solution {
14+
public:
15+
ListNode* reversedListNode(ListNode* head) {
16+
if(head != nullptr && head->next ==nullptr ){
17+
return head;
18+
}
19+
ListNode *newHead = reversedListNode(head->next);
20+
ListNode *front = head->next;
21+
front->next = head;
22+
head->next = nullptr;
23+
return newHead;
24+
25+
}
26+
ListNode* reverseList(ListNode* head) {
27+
ListNode *prev = nullptr;
28+
ListNode *temp = head;
29+
if(temp != nullptr) {
30+
return reversedListNode(temp);
31+
}
32+
else {
33+
return temp;
34+
}
35+
}
36+
};

0 commit comments

Comments
 (0)