好像有颱風要來,天氣變得有點冷
題號:24 標題:Swap Nodes in Pairs 難度:Medium
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
Example 1:
我的程式碼
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null || head.next == null){
return head;
}else{
ListNode f = new ListNode();
ListNode s = new ListNode();
ListNode c = new ListNode();
ListNode temp = new ListNode();
f = head;
s = head.next;
if(head.next==null){
head =head.next;
head.next = f;
return head;
}
head = head.next;
c= head.next;
//System.out.print("i: "+ c.val+" ");
int i =1;
while(s!=null){
System.out.print(i+": "+ s.val+" ");
s.next = f;
temp.next = s;
if(c!=null){
f.next = c;
c = c.next;
if(c != null){
c = c.next;
}
}else{
f.next = null;
}
temp = f;
f = f.next;
s = s.next;
s = s.next;
if(s == null){
break;
}
s = s.next;
// System.out.print(i+": "+ cur.val+" ");
// System.out.print(i+": "+(cur.next).val +" ");
// System.out.println(i+": "+(p).val);
}
}
return head;
}
}
邏輯
把前一個指向現在的下一個,現在的指向前一個。
DAY24心得
我覺得我跟LINKLIST真的有比較熟了,開心