好像有台风要来,天气变得有点冷
题号: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真的有比较熟了,开心
该文章同步发布於:我的部落格 在我一开始学习写 Rails 测试时,会有很常见的问题,就是到底什麽...
接续昨天的练习:https://ithelp.ithome.com.tw/articles/1026...
接着我们说明optimizer设定 。 首先,我们先得知道 training and validat...
倒数第二篇~ 来个不分类的杂七杂八问题篇, 有些问题,不知道该怎麽分类, 而有些分类,这次没机会写到...
1.阵列:一、二、三维 $a[0] = 123; // 一维 $a[1][0] = 10; // 二...