C++合并链表,利用VS studio完整调试过程(含测试)

首先,先来看看题目:合并两个排序的链表
输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。


示例图片

题目本身不多XX,直接上代码(重要的是,第一次学着用VS studio测试调试),其中如何输入链表,测试函数最好能够记忆一下:ListNode 结构体、mergeTwoLists函数为合并的算法函数、createList()函数为创建链表(链表值为用户输入,注意回车停止输入的方法!)、main()函数用来测试:

#include <iostream>
using namespace std;
#include <string.h> 
struct ListNode {
     int val;
     ListNode *next;
     ListNode(int x) : val(x), next(NULL) {}
 };

ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
    if (!l1) return l2;
    if (!l2) return l1;
    if (l1->val >= l2->val) {
        l2->next = mergeTwoLists(l1, l2->next);
        return l2;
    }
    if (l1->val < l2->val) {
        l1->next = mergeTwoLists(l1->next, l2);
        return l1;
    }
    return l2;
}

ListNode* createList()
{
    cout << "请输入链表节点并以0作为结尾:" << endl;
    //用到的变量
    ListNode *p_new = NULL;
    ListNode *p_old = NULL;
    int n;
    //建立尾结点
    cin >> n;
    ListNode *head = new ListNode(n);
    head->next = NULL;

    //循环建立后续节点
    p_old = head;
    int cycle = 1;
    while (cycle)
    {
        cin >> n;
        if (n != 0)
        {
            ListNode *p_new = new ListNode(n);
            p_old->next = p_new;
            p_old = p_old->next;
            p_new->next = NULL;
        }
        else
        {
            cycle = 0;
            cout << "Input done! " << endl;
        }
    }
    return head;
}
void print_list( ListNode* L1 ){
    while (L1) {
        cout << L1->val<<"----";
        L1 = L1->next;
    }
    cout << endl;
}
void main() {
    ListNode* L1 = createList();
    ListNode* L2 = createList();
    ListNode* L3 = mergeTwoLists(L1, L2);
    print_list(L3);
    system("pause");
}

首先在调试的过程中可以打断点:


步骤1

然后开始调试,(没调试一个断点后,点击继续继续调试),在断点调试的过程当中可以利用调试----->窗口---->自动窗口监视变量的情况,如图所示,输入链表L1为12345,(虽然我还是用了print函数来打印更直观的看):


步骤2

最终结果如下所示:


最终结果
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 题目类型 a.C++与C差异(1-18) 1.C和C++中struct有什么区别? C没有Protection行为...
    阿面a阅读 7,714评论 0 10
  • Python语言特性 1 Python的函数参数传递 看两个如下例子,分析运行结果: 代码一: a = 1 def...
    伊森H阅读 3,083评论 0 15
  • 下面是我整理的,剑指Offer前五章所有的题目以及相关题和拓展题的题目和答案。代码的话放在github上,您可以下...
    kikido阅读 1,056评论 0 1
  • Python语言特性 1 Python的函数参数传递 看两个如下例子,分析运行结果: 代码一: a = 1 def...
    时光清浅03阅读 504评论 0 0
  • 转载请注明出处:http://www.jianshu.com/p/c65d9d753c31 在上一篇博客《数据结构...
    Alent阅读 3,535评论 4 74