[leetcode]Swap Nodes in Pairs Reverse Nodes in k-Group

来源:互联网 发布:粘土淘宝 编辑:程序博客网 时间:2024/04/30 03:08

Swap Nodes in Pairs     Reverse Nodes in k-Group

题意:将一个链表,每k个元素翻转一次。

解法:首先获取链表的长度,确定有几个要翻转的序列。接下来每次读取k个元素,组成翻转后的list,加入ans。

public class Solution128 {   public ListNode reverseKGroup(ListNode head, int k) {       ListNode temp=head;       if (k==0||k==1){                return head;       }       int n=0;       while(temp!=null){                n++;                temp=temp.next;       }       if (n<k){                return head;       }        int a=n / k;       temp=head;       ListNode ansHead=null;       ListNode ansTail=null;       for (int i=0;i<a;i++){                ListNode tempHead=temp;                ListNode tempTail=temp;                temp=temp.next;                for (intj=0;j<k-1;j++){                                                  ListNodethisPoint=temp;                          temp=temp.next;                          thisPoint.next=tempHead;                          tempHead=thisPoint;                }                if (ansHead==null){                          ansHead=tempHead;                          ansTail=tempTail;                }else{                          ansTail.next=tempHead;                          ansTail=tempTail;                }                      }       ansTail.next=temp;       return ansHead;    }}


0 0
原创粉丝点击