LinkedList All Operations
npm install linked-list-packbash
npm i linked-list-pack
`
Usage
Import the package in your project:
`javascript
const {
LinkedList,
ListNode,
reverseList,
mergeTwoLists,
removeNthFromEnd,
hasCycle,
getIntersectionNode,
addTwoNumbers,
isPalindrome,
deleteDuplicates
} = require('linked-list-utilities');
`
$3
Create and manage linked lists easily using the LinkedList class.
`javascript
const list = new LinkedList();
list.addNode(1);
list.addNode(2);
list.addNode(3);
list.printList(); // Output: 1 -> 2 -> 3
list.updateNode(2, 5);
list.printList(); // Output: 1 -> 5 -> 3
list.deleteNode(5);
list.printList(); // Output: 1 -> 3
`
$3
1. reverseList(head): Reverses a linked list.
- Input: head (ListNode) - Head of the linked list.
- Output: (ListNode) - New head of the reversed list.
`javascript
const reversedHead = reverseList(list.head);
`
2. mergeTwoLists(list1, list2): Merges two sorted linked lists into one sorted list.
- Input: list1, list2 (ListNode) - Heads of the two sorted linked lists.
- Output: (ListNode) - Head of the merged list.
`javascript
const mergedHead = mergeTwoLists(list1, list2);
`
3. removeNthFromEnd(head, n): Removes the Nth node from the end of the list.
- Input: head (ListNode) - Head of the linked list, n (number) - Position from the end.
- Output: (ListNode) - Head of the modified list.
`javascript
const newHead = removeNthFromEnd(list.head, 2);
`
4. hasCycle(head): Detects if a linked list has a cycle.
- Input: head (ListNode) - Head of the linked list.
- Output: (boolean) - true if the list has a cycle, false otherwise.
`javascript
const cycleExists = hasCycle(list.head);
`
5. getIntersectionNode(headA, headB): Finds the intersection node of two linked lists.
- Input: headA, headB (ListNode) - Heads of the two linked lists.
- Output: (ListNode) - Intersection node or null.
`javascript
const intersectionNode = getIntersectionNode(headA, headB);
`
6. addTwoNumbers(l1, l2): Adds two numbers represented by linked lists.
- Input: l1, l2 (ListNode) - Heads of the two linked lists.
- Output: (ListNode) - Head of the linked list representing the sum.
`javascript
const sumList = addTwoNumbers(list1, list2);
`
7. isPalindrome(head): Checks if a linked list is a palindrome.
- Input: head (ListNode) - Head of the linked list.
- Output: (boolean) - true if the list is a palindrome, false otherwise.
`javascript
const isListPalindrome = isPalindrome(list.head);
`
8. deleteDuplicates(head): Removes duplicates from a sorted linked list.
- Input: head (ListNode) - Head of the sorted linked list.
- Output: (ListNode) - Head of the modified list.
`javascript
const uniqueList = deleteDuplicates(list.head);
``