牛客题霸--链表中的节点每k个一组翻转--题解
链表中的节点每k个一组翻转
https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e?tpId=117&&tqId=34971&rp=1&ru=/ta/job-code-high&qru=/ta/job-code-high/question-ranking
牛客题霸题目链接:链表中的节点每k个一组翻转
https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e?tpId=117&&tqId=34971&rp=1&ru=/ta/job-code-high&qru=/ta/job-code-high/question-ranking
这个题目属于高频面试题,希望大家多多练习,也是入门必备
class Solution { public ListNode reverseKGroup(ListNode head, int k) { ListNode dummy=new ListNode(); dummy.next=head; //定义两个指针 ListNode start=dummy; ListNode end=dummy; while(end!=null){ for(int i=0;i<k && end!=null;i++){ end=end.next; } if(end==null)break; ListNode temp1=end.next; ListNode temp2=start.next; end.next=null; //找到尾部,进行反转 start.next=reverse(temp2); temp2.next=temp1; start=temp2; end=temp2; } return dummy.next; } //单个链表反转方法 public ListNode reverse(ListNode head){ ListNode pre=null; while(head!=null){ ListNode temp=head.next; head.next=pre; pre=head; head=temp; } return pre; } }