题目1
将整个链表反转
private LeetCodeNode revertNodeList(LeetCodeNode head) {
if(head==null||head.next==null){
return head;
}
LeetCodeNode ready = null;
LeetCodeNode cur = head;
LeetCodeNode next = null;
while(cur!=null){
next = cur.next;
cur.next = ready;
ready = cur;
cur = next;
}
return ready;
}
题目2
将链表中M~N区间内的子链表进行翻转
private LeetCodeNode revertMNNode(LeetCodeNode head, int start, int end) {
LeetCodeNode d = new LeetCodeNode();
d.next = head;
LeetCodeNode prev = d;
LeetCodeNode tail = head;
int tmp = start;
while(tmp>1){
tmp--;
prev = tail;
tail = tail.next;
}
LeetCodeNode ready = null;
LeetCodeNode cur = tail;
LeetCodeNode next = null;
tmp = end - start + 1;
while(tmp>0){
next = cur.next;
cur.next = ready;
ready = cur;
cur = next;
tmp--;
}
//由于是从tail(cur)开始倒序的,所以可以通过prev位置将头部和倒序后的链表串联
prev.next = ready;
//倒序后,原先在头的位置,就变成了尾部,直接通过尾部关联剩余的就行
tail.next = next;
return d.next;
}
题目3
将链表以K个元素为一组进行反转
private LeetCodeNode revertKGroup(LeetCodeNode head, int k) {
if(head==null||head.next==null){
return head;
}
LeetCodeNode tail = head;
for (int i = 0; i < k; i++) {
if(tail==null){
return head;
}
tail = tail.next;
}
LeetCodeNode newNode = revertHeadTail(head,tail);
head.next = revertKGroup(tail,k);
return newNode;
}
private LeetCodeNode revertHeadTail(LeetCodeNode head, LeetCodeNode tail){
LeetCodeNode ready = null;
LeetCodeNode cur = head;
LeetCodeNode next = null;
while(cur!=tail){
next = cur.next;
cur.next=ready;
ready = cur;
cur = next;
}
return ready;
}