FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
algorithm-examples/cpp-algorithm/src/linkedlist/shift_list.h at main · codejsha/algorithm-examples · GitHub
codejsha
/
algorithm-examples
Public
Notifications
You must be signed in to change notification settings
Fork
0
Star
2
Code
Issues
0
Pull requests
0
Discussions
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Discussions
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
algorithm-examples
/
cpp-algorithm
/
src
/
linkedlist
/
shift_list.h
Copy path
More file actions
More file actions
Latest commit
History
History
History
67 lines (58 loc) · 1.69 KB
Breadcrumbs
algorithm-examples
/
cpp-algorithm
/
src
/
linkedlist
/
shift_list.h
Copy path
File metadata and controls
67 lines (58 loc) · 1.69 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#
ifndef
CPP_ALGORITHM_SHIFT_LIST_H
#
define
CPP_ALGORITHM_SHIFT_LIST_H
#
include
"
linked_list.h
"
namespace
ShiftList
{
/*
*
* \brief Implement cyclic right shift for a singly linked list.
* Given a singly linked list and an integer k, cyclically right shift the list by k.
* \details Connect the tail to the head to make a cycle,
* apply shift operation to the head to make a cycle, disconnect the cycle.
* For example, 1->2->3->4->5->nullptr and k = 2, return 4->5->1->2->3->nullptr.
* \param list the head of the list
* \param k k shifts
* \return the head of modified list
*/
std::shared_ptr<LinkedList::Node<
int
>>
CyclicallyRightShiftList
(
std::shared_ptr<LinkedList::Node<
int
>>& list,
int
k);
}
//
----------------------------------------------------------------------------
inline
std::shared_ptr<LinkedList::Node<
int
>>
ShiftList::CyclicallyRightShiftList
(
std::shared_ptr<LinkedList::Node<
int
>>& list,
int
k)
{
//
empty list
if
(!list)
{
return
list;
}
//
get the tail and compute the length of the list
auto
tail = list;
int
length =
1
;
while
(tail->
next
)
{
++length;
tail = tail->
next
;
}
//
no shift (k is a multiple of length)
k %= length;
if
(k ==
0
)
{
return
list;
}
//
connect the tail to the head to make a cycle
tail->
next
= list;
//
apply shift operation
int
steps_to_new_head = length - k;
auto
new_tail = tail;
while
(steps_to_new_head--)
{
new_tail = new_tail->
next
;
}
auto
new_head = new_tail->
next
;
//
disconnect the cycle
new_tail->
next
=
nullptr
;
return
new_head;
}
#
endif
Back
|
FazBrowse Home
|
New Git URL