您的位置:首页 > 其它

511- 交换链表当中两个节点

2017-09-07 18:41 351 查看
2017.9.7

链表的东西本来不难,难得是需要后期维护链表。

需要格外注意头结点和尾节点。

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param l1: the first list
* @param l2: the second list
* @return: the sum list of l1 and l2
*/
public ListNode addLists2(ListNode l1, ListNode l2) {
// write your code here
if(l1 == null){
return l2;
}
if(l2 == null){
return l1;
}
String s1 = "";
String s2 = "";
while(l1 != null){
s1 = s1+ Integer.toString(l1.val);
l1 = l1.next;
}
while(l2 != null){
s2 = s2 + Integer.toString(l2.val);
l2 = l2.next;
}
int length1 = s1.length() -1;
int length2 = s2.length() -1;
int flag = 0;
ListNode head = new ListNode(-1);
ListNode tmp = head;
while(length1 >= 0 && length2 >= 0){
int t = s1.charAt(length1) + s2.charAt(length2) -'0'-'0' + flag;
flag = t/10;
t = t%10;
ListNode newNode = new ListNode(t);
newNode.next = head.next;
head.next = newNode;
length1 --;
length2 --;
//System.out.println("t:" + t);
}
while(length1 >=0 ){
int t = s1.charAt(length1) -'0' + flag;
flag = t/10;
t = t%10;
ListNode newNode = new ListNode(t);
newNode.next = head.next;
head.next = newNode;
length1 --;
}
while(length2 >=0 ){
int t = s2.charAt(length2) -'0' + flag;
flag = t/10;
t = t%10;
ListNode newNode = new ListNode(t);
newNode.next = head.next;
head.next = newNode;
length2 --;
}
if(flag == 1){
ListNode newNode = new ListNode(1);
newNode.next = head.next;
head.next = newNode;
}
return head.next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: