编写一个程序,完成如下功能: 1)将用户输入的十进制整数字符串转化为带头结点的单链表每个结点存放一个整数位。 2)求两个整数单链表相加的结果单链表。 3)求结果单链表的中间位,如 123 的中间位为 2,1234 的中间位为 2。 本实验中设计的整数单链表的结点类型如下: typedef struct node{ int data; struct *node; }功能算法设计如下: CreateLink( NodeType *&h, char a[], int n ):创建整数单链表h。 DestroyLink( NodeType *&h ):释放整数单链表h。 DispLink( NodeType *h ):输出整数单链表h。 Add( NodeType *hl,*h2, NodeType *&h ):两整数单链表h1和h2相加得到h。 Reverse( *&h ):逆置整数单链表h。 Mid( NodeType *h ):求整数单链表h的中间位。请给出完整代码并解释
时间: 2023-06-09 18:04:43 浏览: 116
head, char *str )
{
int len = strlen(str);
NodeType *p = head;
int i;
for( i = len - 1; i >= 0; i-- )
{
NodeType *newNode = (NodeType *)malloc(sizeof(NodeType));
newNode->data = str[i] - '0';
newNode->next = NULL;
p->next = newNode;
p = p->next;
}
}
NodeType* Add( NodeType *head1, NodeType *head2 )
{
NodeType *p = head1->next;
NodeType *q = head2->next;
NodeType *newHead = (NodeType *)malloc(sizeof(NodeType));
NodeType *r = newHead;
int carry = 0;
while( p && q )
{
int sum = p->data + q->data + carry;
carry = sum / 10;
NodeType *newNode = (NodeType *)malloc(sizeof(NodeType));
newNode->data = sum % 10;
newNode->next = NULL;
r->next = newNode;
r = r->next;
p = p->next;
q = q->next;
}
while( p )
{
int sum = p->data + carry;
carry = sum / 10;
NodeType *newNode = (NodeType *)malloc(sizeof(NodeType));
newNode->data = sum % 10;
newNode->next = NULL;
r->next = newNode;
r = r->next;
p = p->next;
}
while( q )
{
int sum = q->data + carry;
carry = sum / 10;
NodeType *newNode = (NodeType *)malloc(sizeof(NodeType));
newNode->data = sum % 10;
newNode->next = NULL;
r->next = newNode;
r = r->next;
q = q->next;
}
if( carry )
{
NodeType *newNode = (NodeType *)malloc(sizeof(NodeType));
newNode->data = carry;
newNode->next = NULL;
r->next = newNode;
r = r->next;
}
return newHead;
}
int FindMid( NodeType *head )
{
NodeType *p = head->next;
NodeType *q = head->next;
while( p && p->next )
{
p = p->next->next;
q = q->next;
}
return q->data;
}
阅读全文