-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathK reverse linked list.cpp
50 lines (42 loc) · 1.09 KB
/
K reverse linked list.cpp
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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
ListNode* Solution::reverseList(ListNode* A, int B) {
ListNode *current = A;
ListNode *prev = NULL, *next = NULL,*last=NULL,*last1=NULL;
int i =0,j=0;
if(B!=1){
while (i<B && current!=NULL)
{
if(i==0){
last1=current;
}
if(last){
last->next = current;
}
// Store next
next = current->next;
// Reverse current node's pointer
current->next = prev;
// Move pointers one position ahead.
prev = current;
current = next;
i++;
if(i==B){
if(j==0){
A = prev;
j++;
}
prev = NULL;
i=0;
last = last1;
}
}
}
return A;
}