标签:
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you shouldreturn the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modifythe values in the list, only nodes itself can be changed.
HideTags
#pragma once #include<iostream> #include<queue> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; ListNode *swapPairs(ListNode *head) { if (!head||!head->next) return head; ListNode* result = head->next;//记录返回串的头指针 ListNode *p1 = head->next, *p2 = head;//指向p的前一个节点 //头部添加一个冗余节点,使三指针的初始状态与中间状态相同 ListNode* p3=new ListNode(0); p3->next = p2; while (p1) { p3->next = p1; p1 = p1->next; p2->next->next = p2; p2->next = p1; if (p1) { p3 = p2; p2 = p1; p1 = p1->next; } } return result; } void main() { ListNode* l1 = new ListNode(1); ListNode* l2 = new ListNode(2); ListNode* l3 = new ListNode(3); ListNode* l4 = new ListNode(4); ListNode* l5 = new ListNode(5); l1->next = l2; l2->next = l3; l3->next = l4; l4->next = l5; ListNode* result = swapPairs(l1); while (result) { cout << result->val << ' '; result = result->next; } cout << endl; system("pause"); }
标签:
原文地址:http://blog.csdn.net/hgqqtql/article/details/43691745