計算兩個鏈表的和

結算兩個鏈表的和

package algrothms;

class Node {
	int val;
	Node next;

	public Node(int val) {
		this.val = val;
		this.next = null;
	}

	public Node(int val, Node next) {
		this.val = val;
		this.next = next;
	}

}

public class ReverseList {
	public static Node reverseList(Node head) {// 鏈表反轉算法
		if (head == null) {
			System.out.println("head is null");
			return head;
		} else if (head.next == null) {
			System.out.println("head.next is null");
			return head;
		}
		Node pre = null, q = null;
		while (head != null) {
			q = head.next;// q臨時指向下一個節點
			head.next = pre;// 指向已反轉的鏈表頭,指向當前要反轉節點,初始時已反轉鏈表爲空
			pre = head;
			head = q;
		}
		head = pre;

		return head;

	}

	public static Node calcSum(Node l1, Node l2) {
		if (l1 == null)
			return l2;
		if (l2 == null)
			return l1;
		Node tmp1 = l1, tmp2 = l2, pre = null;
		int i = 0, vv = tmp2.val;
		boolean t = false;
		while (tmp1 != null) {// 以第一個鏈表爲模板再次基礎上運算

			System.out.println("第" + (++i) + "次循環,tmp1.val:[" + tmp1.val + "],tmp2.val:[" + vv + "]");
			tmp1.val = tmp1.val + vv;
			System.out.println("初始和:" + tmp1.val);
			if (tmp1.val >= 10 && tmp1.next != null) {
				tmp1.val = tmp1.val % 10;
				System.out.println("滿十進一後結果:" + tmp1.val);
				tmp1.next.val += 1;
			} else if (tmp1.val >= 10 && tmp1.next == null) {
				tmp1.val = tmp1.val % 10;
				Node f = new Node(1);
				tmp1.next = f;
				t = true;
			}

			pre = tmp1;
			tmp1 = tmp1.next;
			if (tmp2 != null) {
				tmp2 = tmp2.next;
				if (tmp2 != null)// 判空
					vv = tmp2.val;
				else
					vv = 0;
			}

		}
		pre.next = tmp2;
		return l1;

	}

	public static void main(String[] args) {
		Node n1 = new Node(1);
		Node n2 = new Node(2, n1);
		Node n3 = new Node(3, n2);
		Node n4 = new Node(4, n3);
		Node n5 = new Node(5, n4);
		Node n = reverseList(n5);
		Node n6 = new Node(6);
		Node n7 = new Node(7, n6);
		Node n8 = new Node(8, n7);
		Node n9 = new Node(9, n8);
		Node n10 = new Node(9, n9);
		Node n11 = new Node(9, n10);
		Node n12 = new Node(9, n11);
		Node n13 = new Node(9, n12);
		Node n14 = new Node(9, n13);
		Node nn = reverseList(n14);
//		while (n != null) {
//			System.out.println("val:" + n.val);
//			n = n.next;
//		}
		Node calcR = calcSum(n, nn);
		Node calcR1 = calcR;
		int i = 0;
		while (calcR != null) {
			System.out.println("第" + (++i) + "個r.val:" + calcR.val);
			calcR = calcR.next;
		}
		Node result = reverseList(calcR1);

	}

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章