-
Notifications
You must be signed in to change notification settings - Fork 670
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
feb83a8
commit 0c41ba6
Showing
3 changed files
with
56 additions
and
4 deletions.
There are no files selected for viewing
10 changes: 6 additions & 4 deletions
10
C++/Added Set Matrix Zeroes → C++/Added Set Matrix Zeroes.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
File renamed without changes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
#include <iostream> | ||
|
||
struct Node { | ||
int data; | ||
Node* next; | ||
Node(int val) : data(val), next(nullptr) {} | ||
}; | ||
|
||
// Function to reverse a singly linked list | ||
Node* reverseLinkedList(Node* head) { | ||
Node* prev = nullptr; | ||
Node* current = head; | ||
Node* next = nullptr; | ||
|
||
while (current != nullptr) { | ||
next = current->next; // Store the next node | ||
current->next = prev; // Change the current node's next to the previous node | ||
prev = current; // Move the previous pointer to the current node | ||
current = next; // Move the current pointer to the next node | ||
} | ||
|
||
return prev; // New head of the reversed list | ||
} | ||
|
||
// Function to print a linked list | ||
void printLinkedList(Node* head) { | ||
Node* current = head; | ||
while (current != nullptr) { | ||
std::cout << current->data << " -> "; | ||
current = current->next; | ||
} | ||
std::cout << "nullptr" << std::endl; | ||
} | ||
|
||
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); | ||
|
||
std::cout << "Original linked list: "; | ||
printLinkedList(head); | ||
|
||
head = reverseLinkedList(head); | ||
|
||
std::cout << "Reversed linked list: "; | ||
printLinkedList(head); | ||
|
||
return 0; | ||
} |