C/C++ 链表笔试编程题汇总(更新中...)

1.C++:输入一个链表,按链表从尾到头的顺序返回一个ArrayList

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector printListFromTailToHead(ListNode* head) {
        vector ArrayList;//题目中需要返回vector类型
        if(head != NULL)
        {
            ArrayList.insert(ArrayList.begin(), head->val);//先插入第一个数
            while(head->next != NULL)//如果原链表后面还有数就依次向后移动指针 
            {
                head = head->next;
                ArrayList.insert(ArrayList.begin(), head->val);//每次都用头插法插入最终得到逆序
            }
        }
        return ArrayList;
    }
};

2.C:实现单链表的逆转函数

/*
只需要完成逆置链表函数
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};
*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        ListNode* temp = pHead;//temp指针保证正序链表不断开
        ListNode* pre = NULL;//pre指针始终指向逆序的最后一个
        while(temp != NULL){
            temp = pHead->next;//先保存后面的链表 从temp开始
            pHead->next = pre;//正序的第一个去指向逆序的最后一个 成功反转一个结点
            pre = pHead;//移动 pre指针始终指向逆序的最后一个
            pHead = temp; //再次回到初始状态          
        }
        return pre;
    }
};

 

你可能感兴趣的:(C/C++ 链表笔试编程题汇总(更新中...))