LeetCode【328.奇偶連結串列】
阿新 • • 發佈:2018-11-30
奇偶連結串列
給定一個單鏈表,把所有的奇數節點和偶數節點分別排在一起。請注意,這裡的寄數節點和偶數節點指的是節點編號的奇偶性,而不是節點的值的奇偶性。
示例 1
- 輸入:
- 輸出:
示例 2:
- 輸入:
- 輸出:
思路 1
首先,可以初始化兩個節點,一個用來連線奇數節點,一個用來連線偶數節點(這個最後的指標需等於null),因為當連結串列中的節點數目是奇數個時,偶數節點的最後一個節點沒有指向空,可能會造成迴圈連結串列
;。
程式碼 1
class Solution {
public ListNode oddEvenList(ListNode head) {
ListNode OddNode=new ListNode(0);
ListNode EvenNode=new ListNode(0);
ListNode cur=head,ptr=EvenNode,qtr=OddNode;//ptr 記錄EvenNode初始位置,qtr 記錄 OddNode初始位置
while(cur!=null){ //奇數給OddNode,偶數給EvenNode
OddNode.next=cur;
OddNode=OddNode.next;
cur=cur.next;
if(cur!=null){
EvenNode.next=cur;
EvenNode=EvenNode.next;
cur=cur.next;
}
}
EvenNode.next=null;
OddNode.next=ptr.next; //連結奇偶連表
return qtr.next;
}
}
複雜度分析
- 時間複雜度:
- 空間複雜度:
思路 2
直接在給出的連結串列上進行改動指標的指向,來達到題意的要求,奇數和偶數都是每隔一個節點,偶節點可以看作快指標,最後返回head.
程式碼 2
class Solution {
public ListNode oddEvenList(ListNode head) {
if(head == null || head.next == null) {
return head;
}
ListNode odd = head, even = head.next, evenHead = even;
while(even != null && even.next != null) {
odd.next = odd.next.next;
even.next = even.next.next;
odd = odd.next;
even = even.next;
}
odd.next = evenHead;
return head;
}
}
複雜度分析
- 時間複雜度:
- 空間複雜度:
完整程式碼
package leetcode328;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Created by 張超帥 on 2018/10/19.
*/
class ListNode {
int val;
ListNode next;
ListNode (int val){this.val = val;}
}
class Solution {
public ListNode oddEvenList(ListNode head){
if(head == null || head.next == null){
return head;
}
ListNode odd = head, even = head.next, evenHead = even;
while(even != null && even.next != null){
odd.next = odd.next.next;
even.next = even.next.next;
odd = odd.next;
even = even.next;
}
odd.next = evenHead;
return head;
}
}
public class leetcode328 {
public static int[] stringToArrays(String input){
input = input.trim();
input = input.substring(1, input.length() - 1);
if(input == null){
return new int[0];
}
String[] parts = input.split(",");
int[] res = new int[parts.length];
for(int i = 0; i < parts.length; i ++){
res[i] = Integer.parseInt(parts[i].trim());
}
return res;
}
public static ListNode stringToListNode(String input){
int[] nodes = stringToArrays(input);
ListNode cur = new ListNode(-1);
ListNode dummpy = cur;
for(int node : nodes){
cur.next = new ListNode(node);
cur = cur.next;
}
return dummpy.next;
}
public static String listnodeToString(ListNode head){
if(head == null) {
return "[]";
}
String res = "";
while(head != null){
res += head.val + ", ";
head = head.next;
}
return "[" + res.substring(0, res.length() - 2) + "]";
}
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in) );
String line = null;
while((line = in.readLine()) != null){
ListNode head = stringToListNode(line);
ListNode ret = new Solution().oddEvenList(head);
System.out.println(listnodeToString(ret));
}
}
}