单链表的应用--两个链表相加

java实现
**
* Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode p1=l1; ListNode p2=l2; int sum,carry=0; ListNode dumpyHead=new ListNode(0); ListNode s=dumpyHead; while (null!=p1||null!=p2){ int x=(null!=p1)?p1.val:0; int y=(null!=p2)?p2.val:0; sum=(x+y+carry); s.next=new ListNode(sum%10); s=s.next; carry=sum/10; if(p1!=null) p1=p1.next; if(p2!=null) p2=p2.next; } if(carry>0){ s.next=new ListNode(carry); } return dumpyHead.next; } }

注意这里

1、定义的临时变量s指向头指针与利用C语言临时变量s'第一个有效节点;

2、利用java定义一个对象s

最初A  aa=dumpHead;

    不能  A  aa.next=new A();

而是   aa.next=new A();

 

下面的C实现

/**
 * Definition for singly-linked list.
   struct ListNode {
     int val;
     struct ListNode *next;
  };
 */

typedef struct ListNode* LinkList;  
typedef struct ListNode  Node;

struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    int carry=0;
    LinkList pHead=(LinkList)malloc(sizeof(Node));
    LinkList pTail=pHead;
    pTail->next=NULL;
    LinkList p1=l1;
    LinkList p2=l2;
    while(NULL!=p1||NULL!=p2 )
    {  
      int x = (p1!=NULL)? p1->val:0;
      int y = (p2!=NULL)? p2->val:0;
      int sval=(x+y+carry)%10;
      carry=(x+y+carry)/10;
      LinkList pnew=(LinkList)malloc(sizeof(Node));                                                                                           pnew->val=sval;
      pTail->next=pnew;
      pnew->next=NULL;
      pTail=pnew;
      if(NULL!=p1)     
          p1=p1->next; 
      if(NULL!=p2)
          p2=p2->next; 
     }  
    if(carry>0)
    { LinkList pnew=(LinkList)malloc(sizeof(Node));  
      pnew->val=carry;
      pTail->next=pnew;
      pnew->next=NULL;
      pTail=pnew;
    }
    return pHead->next;
    
}

 

posted @ 2018-08-23 09:57  zjkl_欧了  阅读(376)  评论(0编辑  收藏  举报