Swap Nodes in Pairs

来源:互联网 发布:获取网页限制数据 编辑:程序博客网 时间:2024/06/03 14:39

题目大意:链表中的两个数两两交换


/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode *swapPairs(ListNode *head) {         if(head == NULL || head->next == NULL) {            return head;        }        ListNode *result = head->next;        ListNode *preNode = NULL, *curNode = head, *nextNode = head->next;        while(curNode != NULL && nextNode != NULL) {            curNode->next = nextNode->next;            nextNode->next = curNode;            if(preNode != NULL) {                preNode->next = nextNode;            }            preNode = curNode;            curNode = curNode->next;            if(curNode != NULL) {                nextNode = curNode->next;            }        }        return result;    }};


1 0
原创粉丝点击