-
Notifications
You must be signed in to change notification settings - Fork 83
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #955 from min8grace/main
- Loading branch information
Showing
2 changed files
with
70 additions
and
0 deletions.
There are no files selected for viewing
35 changes: 35 additions & 0 deletions
35
davemin/2024-06-24-1721-Swapping-Nodes-in-a-Linked-List.cs
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,35 @@ | ||
/** | ||
* Definition for singly-linked list. | ||
* public class ListNode { | ||
* public int val; | ||
* public ListNode next; | ||
* public ListNode(int val=0, ListNode next=null) { | ||
* this.val = val; | ||
* this.next = next; | ||
* } | ||
* } | ||
*/ | ||
public class Solution { | ||
public ListNode SwapNodes(ListNode head, int k) { | ||
ListNode firstNode = head; | ||
ListNode secondNode = head; | ||
|
||
while(k-1>0){ | ||
firstNode = firstNode.next; | ||
k--; | ||
} | ||
|
||
// while keeping k-gap, move two node parallelly till the first node ends. | ||
ListNode kStepAhead = firstNode; | ||
while(kStepAhead.next!= null){ | ||
kStepAhead = kStepAhead.next; | ||
secondNode = secondNode.next; | ||
} | ||
// swap two nodes. | ||
int temp = firstNode.val; | ||
firstNode.val = secondNode.val; | ||
secondNode.val = temp; | ||
|
||
return head; | ||
} | ||
} |
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,35 @@ | ||
/** | ||
* Definition for singly-linked list. | ||
* public class ListNode { | ||
* public int val; | ||
* public ListNode next; | ||
* public ListNode(int val=0, ListNode next=null) { | ||
* this.val = val; | ||
* this.next = next; | ||
* } | ||
* } | ||
*/ | ||
public class Solution { | ||
public ListNode RotateRight(ListNode head, int k) { | ||
if (head == null) | ||
{ | ||
return null; | ||
} | ||
ListNode tail = head; | ||
int length = 1; | ||
while(tail.next != null){ | ||
Console.WriteLine(tail.val); | ||
tail = tail.next; | ||
length++; | ||
} | ||
tail.next = head; | ||
k = length - k % length; | ||
while(k>0){ | ||
head = head.next; | ||
tail = tail.next; | ||
k--; | ||
} | ||
tail.next = null; | ||
return head; | ||
} | ||
} |